Reputation: 145
I am trying to create a multi select drop down in Cakephp3. Then update a many to many
I have a post table and tags table and a post_tags table the models have the following foreign keys
PostsTable
$this->hasMany('PostTags', [
'foreignKey' => 'post_id'
]);
TagsTable
$this->hasMany('PostTags', [
'foreignKey' => 'tag_id'
]);
PostTagsTable
$this->belongsTo('Tags', [
'foreignKey' => 'tag_id',
'joinType' => 'INNER'
]);
the post tags table has a post_id and tag_id
in my post add view I have
echo $this->Form->input('tags', ['class'=>'form-control', 'id'=>'select4', 'label' => false, 'options' => $tags, 'multiple' => 'multiple']);
When I debug in the controller I get
'tags' => [
(int) 0 => '1',
(int) 1 => '2'
],
When I look on stack overflow it seems I need to have this: ( I am not 100% sure this is correct) A:
$data = [
'tags' => [
['id' => 1],
['id' => 2]
]
]
I tried looping through the $tags like but the debug results are pretty much the same: Looping like this
<div class="input select">
<input type="hidden" name="tags" value=""id="select4_">
<select name="tags[]" multiple="multiple" class="select4" size="7">
<?php
echo '<option id="tag1" value="tag1">option 1</option>';
echo '<option id="tag2" value="tag2" >option 2</option>';
?>
</select>
</div>
I will get
'tags' => [
(int) 0 => 'tag1',
(int) 1 => 'tag2'
],
Apparently I need to pass the values as shown in A: to the controller and then do
$post = $this->Posts->patchEntity($post, $this->request->data, ['associated' => ['Tags']]);
To make it all work. I would appreciate some help on this as I have been struggeling for days with this. Thanks
Upvotes: 0
Views: 478
Reputation: 457
You'll want this in your template:
echo $this->Form->input('tags._ids', [
'type' => 'select',
'multiple' => true,
'options' => $tags,
]);
Then the Cake marshaller should fix it itself :) Make sure the entity has this property as accessible though! :-)
You can see the docs in action here: http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data
Upvotes: 0