user1521944
user1521944

Reputation: 337

CakePHP3 Many to Many relations

i am trying to save a form which has many to many relation in CakePHP3 but I can't render the form properly. (user HABTM tags)

In my controller i set the object that i want to edit:

$user = $this->Users->get($id, [
    'contain' => ['Tags']
]);
$this->set(compact('user'));

In the view I have:

$options = [
    '1' => 'Tag 1',
    '2' => 'Tag 2'
];
echo $this->Form->select('tags', $options, [
    'multiple' => 'checkbox'
]);

My problem is on the load the selected tags are not checked, how I can solve this ?

Upvotes: 0

Views: 1283

Answers (1)

ndm
ndm

Reputation: 60503

For such a belongsToMany association you should make use of the _ids key in the fieldname, that way the form helper can magically pick up the values and check your boxes.

$this->Form->select('tags._ids',  /* ... */);

See

for some info.

Also you should retrieve the list of tags from your table instead of defining them manually in the view

controller

// ...
$tags = $this->Users->Tags->find('list');
$this->set(compact('user', 'tags'));

view

echo $this->Form->select('tags._ids', $tags, [
    'multiple' => 'checkbox'
]);

See also Cookbook > Finding Key/Value Pairs

Upvotes: 3

Related Questions