Reputation: 3664
Mycakephp version is 2.1.1.
i am trying to save the associated model manually using saveAll() function
Model
so table
employees(first_name,last_name,age,sex,department_id)
addresses(first_line,second_line,city,state,employee_id)
now employee creation add.ctp has a form which receives input for employee and address
i know
$this->Employee->saveAll($this->request->data);
this will save the models but
i want to save the association manually
i was going through the official cakephp document here and i have tried something like this
$this->Employee->saveAll($data, array(
'fieldList' => array(
'Employee' => array('first_name','last_name','age','sex','department_id'),
'Department' => array('first_line', 'second_line','city','state','employee_id')
)
));
it is not working , and throws following errors
Notice (8): Undefined variable: data [APP\Controller\EmployeesController.php, line 118]
Warning (2): array_keys() expects parameter 1 to be array, null given [CORE\Cake\Model\Model.php, line 1996]
i am cakephp beginner. please help me.
$this->request->data: Array
(
[Employee] => Array
(
[first_name] => Jack
[last_name] => Robert
[age] => 32
[sex] => 0
[Department] => Development
)
[Address] => Array
(
[first_line] => HSR Layout
[second_line] => 1st Cross
[city] => Najem
[state] => Barel
)
[Department] => Array
(
[id] => 3
)
)
Upvotes: 1
Views: 1048
Reputation: 3664
After doing some research i have found it.
$data = array(
'Employee' => array(
'first_name' => $this->request->data['Employee']['first_name'],
'last_name'=>$this->request->data['Employee']['last_name'],
'age'=>$this->request->data['Employee']['age'],
'sex'=>$this->request->data['Employee']['sex'],
'department_id'=>$this->request->data['Department']['id']
),
'Adress' => array(
'first_line' => $this->request->data['Adress']['first_line'],
'second_line'=>$this->request->data['Adress']['second_line'],
'city'=>$this->request->data['Adress']['city'],
'state'=>$this->request->data['Adress']['state']
)
);
$this->Employee->saveAll($data, array('deep' => true))
this will do it.
Upvotes: 0
Reputation: 5303
Try using just an array in fieldList
parameter:
$this->Employee->saveAll($this->request->data, array('fieldList' => array('Employee.first_name', 'Employee.last_name', 'Employee.age', 'Employee.sex', 'Department.first_line', 'Department.second_line', 'Department.city', 'Department.state', 'Department.employee_id')));
According to manual, fieldList
expects "an array of fields you want to allow for saving". I think not accepted a multidimensional array.
$this->request->data
is all fields of your form, you can check with debug($this->request->data)
.
Upvotes: 0