cakephp - Saving data from hasMany and belongsTo -
i having trouble cakephp. try find answer on forum, nothing usefull in case :( here problem :
i have 2 table :
author | role id | id role_id | name i set author "belongsto role" , role "hasmany author"
on view, form looks :
$this->form->create('role') $this->form->input('name')); $this->form->input('author.id', array('type' => 'select', 'multiple' => true, 'options' => $authors)); my role controller :
function index() { if (!empty($this->data)) { if ($this->role->saveall($this->data)) { } } $this->set('authors', $this->role->author->find('list')); } but when try save, new role in created, create new author row instead of update existing one. want, update role_id author table when create new role. idea what's wrong ?
edit: same result $this->request->data instead of $this->data data looks when create new role assigned 2 authors:
array( 'role' => array( 'name' => 'test', ), 'author' => array( 'id' => array( (int) 0 => '1', (int) 1 => '3' ) ) ) thanks help.
to start save data not in correct format. can't set author.id array, expecting integer therefore isn't updating existing data.
not 100% sure work try rewriting save data this:-
$authorids = hash::extract($this->request->data, 'author.id.{n}'); foreach ($authorids $authorid) { $authors[] = [ 'id' => $authorid ]; } $data = [ 'role' => $this->request->data['role'], 'author' => $authors ]; then use $this->role->saveall($data). (i'm sure there's more elegant way of writing this, quick example code).
Comments
Post a Comment