Forms and mutiple select boxes in many-to-many


How can i retrieve the the values of relational object in form, when i edit ?

In model i have:

             array('alias' => 'categories')

In form i have:

        $this->add(new Text('title'))
             ->add(new Text('slug'))
             ->add(new Text('tags'))
             ->add(new TextArea('content'));

        $this->add(new Select('is_published', array(
                1 => $translate['Yes'],
                0 => $translate['No']
        $this->add(new Select('categories', Category::find(), array(
            'using' => array('id', 'name'),
            'value' => ???

I don't know how can i get the the categories assigned to the current article. Any help please ? PS: I tried $this->getEntity()->categories . But i got stuck.


No one yet here ? :) It should be nice to have an example of crud with many-to-many relations ... just to follow the good practice. Otherwise, i can do it traditionally.


You can use setDefault to set the default value in a form element:

$select = new Select('categories', Category::find(), array(
    'using' => array('id', 'name'),


Thanks Phalcon. It seems that if the Select element is not a multiple type, this does not work. This is one. The second, if i select multiple categories, the save of article fails.

                    'title' => $this->request->getPost('title', 'striptags'),
                    'categories' => $this->request->getPost('categories'),
                    'slug' => $this->request->getPost('slug'),
                    'content' => $this->request->getPost('content'),
                    'is_published' => $this->request->getPost('is_published'),
                    'tags' => $this->request->getPost('tags')

$this->request->getPost('categories') is a select element:

<select multiple="1" name="categories[]"> ... </select>

When posting the data, $this->request->getPost('categories'), is an array and i get this error:

PHP Fatal error:  Phalcon\\Mvc\\Model::_postSaveRelatedRecords(): Call to method save() on a non object


Hi, I have same question here. Calin Rada, did you found the answer yet?


Nope. I still hope that someone will spend a little time to answer to this :)


Yes, using Sync To Attach Many To Many Models ```php $user->roles()->sync(array(1, 2, 3)); ```