cakephp hasMany through and multiselect form

Posted by Zoran Kalinic on Stack Overflow See other posts from Stack Overflow or by Zoran Kalinic
Published on 2012-10-15T13:52:15Z Indexed on 2012/10/15 21:37 UTC
Read the original article Hit count: 220

Filed under:

I'm using cakephp 2.2.2 and I have a problem with the editing view

Models and relationships are:

Person hasMany OrganizationPerson
Organization hasMany OrganizationPerson
OrganizationPerson belongs to Person,Organization

A basic hasMany through relationship as found within cake documentation.

Tables are:

people (id,...)
organizations (id,...)
organization_people (id, person_id,organization_id,...)

In the person add and edit forms there is a select box allowing a user to select multiple organization. The problem I have is, when a user edits an existing person, the associated organizations aren't pre-selected.

Here is the code in the PeopleController:

$organizations = $this->Person->OrganizationPerson->Organization->find('list');
$this->set(compact('organizations'));

Related part of the code in the People/edit code looks like:

$this->Form->input('OrganizationPerson.organization_id', array('multiple' => true, 'empty' => false));

This will populate the select field, but it does not pre-select it with the Person's associated organizations.

Format and content of the $this->data:

Array ( 
    [Person] => Array ( 
        [id] => 1 ... ) 
    [OrganizationPerson] => Array ( 
        [0] => Array ( 
            [id] => 1 
            [person_id] => 1 
            [organization_id] => 1 ... ) 
        [1] => Array ( 
            [id] => 2 
            [person_id] => 1 
            [organization_id] => 2 ... ) ) )

What I have to add/change in the code to get pre-selected organizations?

Thanks in advance!

© Stack Overflow or respective owner

Related posts about cakephp