symfony2 many-to-many form checkbox

二次信任 提交于 2019-12-02 18:07:10

I've used entity type instead of collection. I thing collection is mainly used to actually create a Role object and assign it to User.

If you want to just list all existing roles and be able to select and assign it to the user then:

->add('roles', 'entity', array(
    'class' => 'MyBundle:Role',
    'property'     => 'name',
    'multiple'     => true
));

EDIT: this will render the widget as a multiple <select>, refer to entity type to render as checkbox list.

Symfony3:

In case anyone is using Symfony3:

use Symfony\Bridge\Doctrine\Form\Type\EntityType;

->add('roles', EntityType::class, array( // <-- EntityType::class is unique to Symfony3
    'class' => 'AppBundle:Role',
    'choice_label' => 'name', // <-- choice_label is unique to Symfony3
    'multiple' => true
))
Nicki

@user1041880: If you use the symfony security functions (which needs the roles of th euser as an array), you can do it like this:

->add('rolesAsCollection', 'entity', array(
    'class' => 'MyBundle:Role',
    'property'     => 'name',
    'multiple'     => true
));

And in your user class:

public function getRolesAsCollection()
{
    return $this->roles;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!