Saving data to a new row - cakephp

I have an application with CakePHP and I need to insert some row of data to a table. I have followed the tutorial in the CakePHP book but it doesn't work.
$this->Temporary->create();
$this->Temporary->set(
array(
'Temporary.position_id'=>$employeesAttribute[$arrCount][0]['EmployeeAttribute']['position_id'],
'Temporary.person_id'=>$employeesAttribute[$arrCount][0]['StatusEmployee']['person_id'],
'Temporary.job_id'=>$employeesAttribute[$arrCount][0]['Job']['id'],
'Temporary.unit_id'=>$employeesAttribute[$arrCount][0]['Unit']['id'],
'Temporary.person_code'=>$employeesAttribute[$arrCount][0]['StatusEmployee']['code'],
'Temporary.name'=>$employeesAttribute[$arrCount][0]['Person']['first_name'].' '.$employeesAttribute[$arrCount][0]['Person']['middle_name'].' '.$employeesAttribute[$arrCount][0]['Person']['last_name'],
'Temporary.job'=>$employeesAttribute[$arrCount][0]['Job']['short_desc']
)
);
$this->Temporary->save();
I have used create() method, set the variable and called the save method but this code doesn't save the data to my table. What is wrong with this code?

$this->Temporary->create();
$data =
array(
'Temporary' => array(
'position_id'=>$employeesAttribute[$arrCount][0]['EmployeeAttribute']['position_id'],
'person_id'=>$employeesAttribute[$arrCount][0]['StatusEmployee']['person_id'],
'job_id'=>$employeesAttribute[$arrCount][0]['Job']['id'],
'unit_id'=>$employeesAttribute[$arrCount][0]['Unit']['id'],
'person_code'=>$employeesAttribute[$arrCount][0]['StatusEmployee']['code'],
'name'=>$employeesAttribute[$arrCount][0]['Person']['first_name'].' '.$employeesAttribute[$arrCount][0]['Person']['middle_name'].' '.$employeesAttribute[$arrCount][0]['Person']['last_name'],
'job'=>$employeesAttribute[$arrCount][0]['Job']['short_desc']
)
)
);
$this->Temporary->save($data);

Related

How to put where conditions with group by in cakephp find all query

I have created sql query which is working fine.
But i want to convert this sql query in cakephp format.
I try to convert this query in cakephp but
i am not understanding how to apply where conditions with group by clause.
And i only need to select this column u_data.lane_id AS LaneId, origin_city.pcode AS origin_pcode, dest_city.pcode AS dest_pcode....
not all columns from table.
plz help me to do this.
$options['conditions'] = array(
'CustomerRoute.portfolio_id' => '".$_SESSION["portfolioid"]."'
);
$content = $this->Customer->find('all', $options);
You simply need to define "group" and "fields" within $options-
Instead of $_SESSION, you should stick to the convention and use $this->Session->read instead.
//Eg: $_SESSION["portfolioid"] can be replaced with $this->Session->read("portfolioid")
$options['conditions'] = array(
"CustomerRoute.portfolio_id" => $this->Session->read("portfolioid"),
"u_data.supplier_id" => $this->Session->read("supplierid")
);
$options['fields'] = array(
"u_data.lane_id AS LaneId",
"origin_city.pcode AS origin_pcode",
"dest_city.pcode AS dest_pcode"
); // Add this
$options['group'] = array('CustomerRoute.id'); // Add this
$content = $this->Customer->find('all', $options);
This should give you what you're looking for.
Peace! xD

Data is not getting populated in cakephp

if($this->request->is('post'))
{
$this->loadModel('Ngolist');
if($this->Ngolist->save($this->request->data))
{
$this->Session->setFlash("Success");
$this->redirect(array("action"=>"thoughts"));
}
else
{
$this->Session->setFlash("Fail");
}
}
The above is my code to get input from user(with a textarea) and insert/save that to my database 'ngolist' with two fields 'id' and 'thought'.
But am getting the flash with fail? Can anyone help me out with this?
$this->request->data returns
array(
'NgoLists' => array(
'thought' => 'hi'
)
)
(1)As per the cakephp naming conventions database table name should be ngolists.
http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html#model-and-database-conventions
(2) If this code is written in NgolistsController.php, then remove this line
$this->loadModel('Ngolist'); and add the below line,
$this->Ngolist->create();

Automatically adding additional Records into HABTM table in CakePhp

Iam confused about a problem. i will describe it
I am using HABTM first time in cakephp,also i am not too much familiar with cakephp 2.4.6
I have
MediaOrg- model, media_orgs - table name
table fields- id,name
public $hasAndBelongsToMany = array(
'className' => 'ContactPerson',
'joinTable' => 'contact_people_media_orgs',
'foreignKey' => 'media_org_id',
'associationForeignKey' => 'contact_person_id'
);
ContactPerson -model contact_person- table name
table_fields - id,name,designation,contact_number,ladline
public $hasAndBelongsToMany = 'MediaOrg'
ContactPeopleMediaOrg -model , table name-contat_people_media_orgs
table_fields - contact_person_id ,media_org_id
//now in controller saving values for media_org table
$this->MediaOrg->save($this->request->data)
$media_org_id=$this->MediaOrg->id;
//next in controller saving values for contact_person table
$this->ContactPerson->save($this->request->data)
$mcontact_person_id=$this->ContactPerson->id;
//next saving id's into many-to-many table
$contact_person_mediaorg_table=array('contact_person_id'=>$contact_person_id,
'media_org_id'=>$media_org_id );
$this->ContactPeopleMediaOrg->save($contact_person_mediaorg_table);
everything is working fine. i dont know what happends in the common table
contact_person_media_org , the data is adding 3 tomes.
first time it adding correct id's and next each time it addiing the mobile number and land number of contact person with media_org_id
when i debug it using getDataSource(), i can find that some param is passing to that common table and adding to it. i dont know how it happening
(int) 6 => array('query' => 'INSERT INTO `go4ad`.`contact_people_media_orgs`
(`media_org_id`, `contact_person_id`) VALUES (?,?)',
'params' => array(
(int) 0 => '30',
(int) 1 => '55555555'
),
'affected' => (int) 0,
'numRows' => (int) 0,
'took' => (float) 1
Also i can find that some BEGIN and COMMIT keywords are there.
Actually What is happening..if anyone can help me..pls pls help me. iam stucking
You should use saveAssociated(). Overall, your process should generate something like this:
$this->request->data = array(
'MediaOrg' => array(
'id' => $media_org_id,
),
'ContactPerson' => array(
0 => $first_person_id,
1 => $second_person_id,
2 => $thurd_person_id,
),
);
$this->MediaOrg->saveAssociated($this->request->data);
And it will add rows to your HABTM relation table (media_organization_contact_persons). Now, this works when you have the rows already added to the database, and you want to add the connections. If you want to add data to the tables in the same time, or whatever that this answer doesn't cover for you, you can read this article.

Update a row +1 in CakePHP

I am trying to update a row in the database but haven't found a way to do this in the CakePHP way (unless I query the row to retrieve and update).
UPDATE mytable (field) VALUES (field+1) WHERE id = 1
In CodeIgniter, it would have been as simple as:
$this->db->set('field', 'field+1', FALSE);
$this->db->where('id', 1);
$this->db->update('mytable');
How do I do this without querying the row first, retrieve the value, then updating the row with the information I got?
I don't think CakePHP has a similar method for doing this in a normal save() on a single row.
But the updateAll() method, which updates multiple rows, does support SQL snippets like so:
$this->Widget->updateAll(
array('Widget.numberfield' => 'Widget.numberfield + 1'),
array('Widget.id' => 1)
);
The first param is an array of fields/values to be updated, and the second param are the conditions for which rows to update.
Apart from that I think the only thing is to use:
$this->Widget->query('YOUR SQL QUERY HERE');
Which lets you query with raw SQL. [EDIT: but this is not recommended as it bypasses the ORM.]
Try this
<?php
class WidgetsController extends AppController {
public function someFunction( $id = null ){
if( $id ){
// read all fields from the model
// alternately you can $this->Widget->read( array( 'field' ), $id );
$this->Widget->read( null, $id );
// grab the 'field' field so we don't have to type out the data array
$field = $this->Widget->data[ 'Widget' ][ 'field' ];
// where field is the name of the field to be incremented
$this->Widget->set( 'field', $field + 1 );
$this->Widget->save( );
}
// someday cake devs will learn to spell referrer
$this->redirect( $this->referer( ));
}
}
?>
Basically you are passing the id, if it exists you read the Widget model (see the notes above, null as 1st param read the entire table) and then you are using Model::set to st the field to a value one greater than itself - remember to cast to int if you store the field as a char/varchar - and then save the model.

How do I get the last inserted 'id' from the forms table and add it to the 'form_id' in the attributes table?

I have two tables,Forms and Attributes. I'm tring to retrieve the last inserted id from the Forms table and insert it to the form_id column of the Attributes table, along with the other field columns.
Earlier I retrieved the form Id from the Forms table and used it to update the value of the Form name column. It worked fine.The code for that is given below:
function saveFormName($data)
{
$this->data['Form']['formname']=$data['Form']['formname'];
$this->data['Form']['id']=$this->find('all', array(
'fields' => array('Form.id'),
'order' => 'Form.id DESC'
));
$this->id=$this->data['Form']['id'][0];
$this->saveField('name',$this->data['Form']['formname']);
}
But When I tried to do it in a similar way for updating the attributes table,the row is not saved in the database,since the value of $this->data['Form']['id'][0] is an 'Array'.
Even in the saveFormName function, the value of $this->data['Form']['id'][0] is an 'Array',but the form name gets updated correctly. Someone explain me the concept.
function saveFieldEntries($data)
{
$this->data['Form']['id']=$this->find('all', array(
'fields' => array('Form.id'),
'order' => 'Form.id DESC'
));
$this->data['Attribute']['form_id'] = $this->data['Form']['id'][0];
$this->data['Attribute']['label']= 'Label';
$this->data['Attribute']['size']='20';
$this->data['Attribute']['type']=$data['Attribute']['type'];
$this->data['Attribute']['sequence_no'] = $data['Attribute']['sequence_no'];
$this->Attribute->save($this->data);
}
EDIT:
Ok, here is the corresponding code in the controller.
function insertFormName()
{
$this->data['Form']['formname']=$this->params['form']['formname'];
$this->Form->saveFormName($this->data);
}
function insertFieldEntry()
{
$this->data['Attribute']['type']=$this->params['form']['type'];
$this->data['Attribute']['sequence_no'] = $this->params['form']['sequence_no'];
$this->Form->saveFieldEntries($this->data);
}
The parameters form name,type and sequence no are passed to the controller from the corresponding view file.
$this->data['Form']['id'][0] holds an array because find('all') returns an array.
So if you need first ID from this array, you need to pick it properly in function saveFieldEntries:
...
$this->data['Attribute']['form_id'] = $this->data['Form']['id'][0]['Form']['id'];
...

Resources