Pre-filling multi-checkbox fields using FormHelper


I apologise in advance if this was already covered somewhere. I am using CakePHP 3 (but would also be happy with a solution for CakePHP 4). I am faced with the following problem:

I have two tables, Articles(…) BelongsToMany Tags(id, name, category). I have an edit action on my ArticlesController, in which I load the Article along with its associated Tags and all available tags like this:

$article = $this->Articles->get($articleId, ['contain' => ['Tags']]);
$tags = $this->Tags->find()->combine('id', 'name', 'category')->toArray();
$this->set(compact('article', 'tags'));

I then use $article as context for a FormHelper form in my view:

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

The select boxes are created correctly so I can later use the request data in patchEntity with [ 'associated' => ['Tags' => ['onlyIds' => true]]]. However, the already associated tags are not selected in the output. I suspect this is because the val option for the select input is filled with the array of Tag entities rather than their respective ids, which the MultiCheckboxWidget seems to expect.

I could of course change the line with the select widget as follows:

$this->Form->select('tags', $tags, ['multiple' => 'checkbox', 'val' => Hash::extract($article->tags, '{n}.id')]);

Given how cake usually handles this kind of plumbing on its own, I was wondering whether this is the best way to do it or whether there is some more idiomatic way that I am missing here.

I would appreciate your feedback.

Of course there is, I was just not thinking straight. The right way to do this would have been to use _ids:

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