Forms and mutiple select boxes in many-to-many

Hello,

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

In model i have:

        $this->hasManyToMany(
             "id",
             "ArticlesCategories",
             "article_id",
             "category_id",
             "Category",
             "id",
             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.



35.1k

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.



85.4k

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

$select = new Select('categories', Category::find(), array(
    'using' => array('id', 'name'),
));
$select->setDefault('some-category-id')
$this->add($select);


35.1k

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.

            $article->assign(array(
                    '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


41

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



35.1k

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



41

Yes, using Sync To Attach Many To Many Models

$user->roles()->sync(array(1, 2, 3));