CakePHP save field to associated table - cakephp

I have my 'PatientCase' model with a hasOne relationship to my 'PatientCaseOrder' model. (This table simply stored the patientCase id along with an integer position)
I am using an ajax function to update the position fields in 'PatientCaseOrder' using the function below in my PatientCase controller
public function update_position(){
Configure::write('debug', 0);
$this->autoRender = false;
$this->loadModel('PatientCaseOrder');
$list = $_POST['list'];
$errs = false;
if($list){
foreach($list as $position){
$id = $position[0];
$pos = $position[1];
$this->PatientCase->id = $id;
if(! $this->PatientCase->PatientCaseOrder->saveField('position', $pos))
$errs = true;
}
}
echo json_encode ($errs);
}
I am passing to it an array containing the PatientCaseId and position.
The code produces a 500 server error, where am i going wrong, or am i taking the wrong approach to this?
NOTE: I previously had the position field in the PatientCase model, and this line of code worked with the above segment of code
$this->PatientCase->saveField('position', $pos)

You need to change your controller function for better debugging:
change to Configure::write('debug', 2);
add $this->layout = 'ajax';
and change : if(! $this->PatientCase->PatientCaseOrder->saveField('position', $pos))
$errs = true;
to:
pr($this->PatientCase->PatientCaseOrder->saveField('position', $pos)); die;
and then in your ajax function log the callback
console.log(returned_data);
and check for errors.

Related

CodeIgniter - displaying view based on variable from database

I've been learning codeigniter recently and trying to push an application out. im running into problems with the if else statements displaying views. i am trying to pull in_party from the databaseci_admin_info and display views depending if its set to 1 or 0. its bypassing any condition and just displaying the first view set.
Model
function get_in_par(){
$this->db->select('in_party');
$this->db->from('ci_admin_info');
$query = $this->db->get();
$ret = $query->row();
return $ret->in_party;
}
Controller
public function index(){
$data['title'] = 'Party';
$data['party'] = $this->party_model->get_party();
$data['prov'] = $this->party_model->get_prov_name();
$data['info'] = $this->party_model->get_all();
$data['res'] = $this->party_model->get_party_res();
$data['rank'] = $this->party_model->get_pa_rank();
$this->load->view('admin/includes/_header', $data);
$inpar = $this->party_model->get_in_par();
if(isset($inpar['in_party'])==0){
$this->load->view('admin/party/join');
} else {
$this->load->view('admin/party/index');
}
$this->load->view('admin/includes/_footer');
}
I've tried rearranging it into the parent construct as well and it just bypassed it completely. just trying to make it load the join view if in_party = 0 . i've tried without isset bypasses it as well. i've tried switch but don't think it registered that as well. i think i'm missing something in my model
$query = $this->db->select('*')
->from('ci_admin_info')
->get();
$result = $query->result_array();
return $result[0];
$inpar = $this->party_model->get_in_par();
if(!isset($inpar['in_party']) || $inpar['in_party']=="0"){....

Indirect modification of overloaded element of Illuminate\Support\Collection has no effect

im quite new in laravel framework, and im from codeigniter.
I would like to add new key and value from database
static function m_get_promotion_banner(){
$query = DB::table("promotion_banner")
->select('promotion_banner_id','promotion_link','about_promotion')
->where('promotion_active','1')
->get();
if($query != null){
foreach ($query as $key => $row){
$query[$key]['promotion_image'] = URL::to('home/image/banner/'.$row['promotion_banner_id']);
}
}
return $query;
}
that code was just changed from codeigniter to laravel, since in codeigniter there are no problem in passing a new key and value in foreach statement
but when i tried it in laravel i got this following error :
Indirect modification of overloaded element of Illuminate\Support\Collection has no effect
at HandleExceptions->handleError(8, 'Indirect modification of overloaded element of Illuminate\Support\Collection has no effect', 'C:\xampp\htdocs\laravel-site\application\app\models\main\Main_home_m.php', 653, array('query' => object(Collection), 'row' => array('promotion_banner_id' => 1, 'promotion_link' => 'http://localhost/deal/home/voucher', 'about_promotion' => ''), 'key' => 0))
please guide me how to fix this
thank you (:
The result of a Laravel query will always be a Collection. To add a property to all the objects in this collection, you can use the map function.
$query = $query->map(function ($object) {
// Add the new property
$object->promotion_image = URL::to('home/image/banner/' . $object->promotion_banner_id);
// Return the new object
return $object;
});
Also, you can get and set the properties using actual object properties and not array keys. This makes the code much more readable in my opinion.
For others who needs a solution you can use jsonserialize method to modify the collection.
Such as:
$data = $data->jsonserialize();
//do your changes here now.
The problem is the get is returning a collection of stdObject
Instead of adding the new field to the result of your query, modify the model of what you are returning.
So, assuming you have a PromotionBanner.php model file in your app directory, edit it and then add these 2 blocks of code:
protected $appends = array('promotionImage');
here you just added the custom field. Now you tell the model how to fill it:
public function getPromotionImageAttribute() {
return (url('home/image/banner/'.$this->promotion_banner_id));
}
Now, you get your banners through your model:
static function m_get_promotion_banner(){
return \App\PromotionBanner::where('promotion_active','1')->get();
}
Now you can access your promotionImage propierty in your result
P.D:
In the case you are NOT using a model... Well, just create the file app\PromotionImage.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PromotionImage extends Model
{
protected $appends = array('imageAttribute');
protected $table = 'promotion_banner';
public function getPromotionImageAttribute() {
return (url('home/image/banner/'.$this->promotion_banner_id));
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'promotion_banner_id','promotion_link','about_promotion','promotion_active'
];
just improving, in case you need to pass data inside the query
$url = 'home/image/banner/';
$query = $query->map(function ($object) use ($url) {
// Add the new property
$object->promotion_image = URL::to( $url . $object->promotion_banner_id);
// Return the new object
return $object;
});
I've been struggling with this all evening, and I'm still not sure what my problem is.
I've used ->get() to actually execute the query, and I've tried by ->toArray() and ->jsonserialize() on the data and it didn't fix the problem.
In the end, the work-around I found was this:
$task = Tasks::where("user_id", $userId)->first()->toArray();
$task = json_decode(json_encode($task), true);
$task["foo"] = "bar";
Using json_encode and then json_decode on it again freed it up from whatever was keeping me from editing it.
That's a hacky work-around at best, but if anyone else just needs to push past this problem and get on with their work, this might solve the problem for you.

php code not working in default.ctp page in Cakephp2.8.5

Thanks in advance, I am new to cakephp, i am using cakephp2.8.5 version. Actually i want to write a php code for counting number of records from the mysql database table comparing the ordered date column date values with the current date. I have written the code but my menus are in default.ctp page. In Order Check menu i have to show the count in numbers. default.ctp page lying in app/view/Layout/default.ctp so how to create a count value in php code without using controller.
My code will compare the current date with the table column date and calculates the count.How can i pass the variable $ordCounts into default.ctp page without creating controller page
Which is as below:
<?php
$a = 0;
for($j=0; $j<count($ordCounts) ;$j++)
{
$orderDate = $ordCounts[$j]['carts']['order_date'];
$currentDate = $dateTime;
$diff = strtotime($currentDate) - strtotime($orderDate);
$hour = $diff/(60*60);
if($hour>24)
{
$a++;
}
}
echo $a;
?>
Create beforeRender() method in AppController
public function beforeRender(){
parent::beforeRender();
//here your code
$this->set('a',$a);
}
$a variable will be available in templates
you can create a function of the above code which counts the occurences in AppController like this
function countOccurences(){
$a = 0;
for($j=0; $j<count($ordCounts) ;$j++)
{
$orderDate = $ordCounts[$j]['carts']['order_date'];
$currentDate = $dateTime;
$diff = strtotime($currentDate) - strtotime($orderDate);
$hour = $diff/(60*60);
if($hour>24)
{
$a++;
}
}
return $a;
}
and then call this function in your beforeFilterMethod in AppController
function beforeFilter(){
parent::beforeFilter();
$count = $this->countOccurences();
$this->set('count',$count);
}

joomla - Storing user parameters in custom component issue

Hi for my custom component I need to set some custom parameters for joomla user for membership for checking if the user ni trial period or not and it can be change from the component admin panel for specific user.
The problem arises while retrieving the parameter. I think it is stored in cookie and it isn^t updated. I wrote the code like that to check it.
$user = JFactory::getUser(JRequest::getVar('id','0'));
echo $user->getParam('trialPeriod','0');
to save the value I am useing JHTML booleanlist.
$user->setParam('trialPeriod',$data['trialPeriod']);
$user->save();
Then is stores the value in joomla users table in the row of that user with column of params as;
{"trialPeriod":"0"}
in this situation it echoes the value as 0. Then I am changin the state of trialPeriod var as 1 and storing in db it updates the db as;
{"trialPeriod":"1"}
After all I am refreshing the page where the value is prompt the the screen the the value remains still the same as 0;
To clarify;
First of all there is no problem with saving the param it is changed properly. The problem is retrieving the changed one. The releated piece of code is following;
$user = JFactory::getUser();
$doc = JFactory::getDocument();
if($user->getParam('trialPeriod',0) == 0){
$ed = JFactory::getDate($obj->expirationDate);//obj is user from custom table and there is no problem with getting it.
$isTrialEnd = FALSE;
}else{
$ed = JFactory::getDate($user->getParam('trialExp',0));
$isTrialEnd = TRUE;
}
if($isTrialEnd){
//do something else
}else{
echo $user->getParam('trialPeriod','0');
}
actually big part of the code is unneccessary to explain it but you will get the idea.
What is the solution for this?
Editted.
$app = JFactory::getApplication();
$config = JFactory::getConfig();
$db = $this->getDbo();
$isNew = empty($data['uid']) ? true : false;
$params = JComponentHelper::getParams('com_dratransport');
if($isNew){
// Initialise the table with JUser.
$user = new JUser;
// Prepare the data for the user object.
$username = self::getCreatedUserName($data['type']);
$data['username'] = !empty($data['username']) ? $data['username'] : $username;
$data['password'] = $data['password1'];
$useractivation = $params->get('useractivation');
// Check if the user needs to activate their account.
if (($useractivation == 1) || ($useractivation == 2)) {
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
}else{
$user = JFactory::getUser($data['uid']);
$data['password'] = $data['password1'];
}
$membership = DraTransportHelperArrays::membershipCFG();
$membership = $membership[$data['membership']];
if($data['membership'] == 4)
$data['groups'] = array($params->get('new_usertype',2),$params->get($membership,2));
else
$data['groups'] = array($params->get($membership,2));
$data['name'] = $data['companyName'];
$user->setParam('trialPeriod',$data['trialPeriod']);
// Bind the data.
if (!$user->bind($data)) {
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()));
return false;
}
// Load the users plugin group.
JPluginHelper::importPlugin('user');
// Store the data.
if (!$user->save()) {
$app->enqueuemessage($user->getError());
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError()));
return false;
}
this piece of code is for storing the data releated with the users table.
Turns out this was the fact that Joomla stores the JUser instance in the session that caused the problem.
When changing a user's parameters from the back-end, the changes are not reflected in that user's session, until she logs out and back in again.
We could not find an easy option to modify anther user's active session, so we resorted to the use of a plugin that refreshes the JUser instance in the logged-in users' session, something like the following:
$user = JFactory::getUser();
$session = JFactory::getSession();
if(!$user->guest) {
$session->set('user', new JUser($user->id));
}
(reference: here).

drupal_write_record doesn't take object

In drupal 6 i used to do something like this:
<?php
/*
* CLASS Example
*/
class example {
var $id = NULL;
var $title;
var $body;
.....
// Save
function save() {
$primary_key = ($this->id == NULL ? NULL : 'id');
if (drupal_write_record('mytabble', $this, $primary_key)) {
return TRUE;
} else {
return FALSE;
}
}
}
?>
This worked quite well. But in Drupal 7, the drupal_write_record only takes an array and no longer the object $this. The new db_merge also only takes an array.
Since i want to save the properties of my object to the database, the above code was very handy and generic for all kinds of classes.
Is there an alternative way to write an object to database, or a method to place objectproperties into a an array?
Any help will be appreciated!
Robert
drupal_write_record does take an object or an array. Guess your problem is caused somewhere else.
drupal_write_record($table, &$record, $primary_keys = array())
$record: An object or array representing the record to write, passed in by reference. If inserting a new record, values not provided in $record will be populated in $record and in the database with the default values from the schema, as well as a single serial (auto-increment) field (if present). If updating an existing record, only provided values are updated in the database, and $record is not modified.
More info on drupal_write_record for D7.

Resources