symfony2 many-to-many form checkbox

Aleš picture Aleš · Mar 15, 2012 · Viewed 14.3k times · Source

I have in symfony created 2 entities: User and Role in many-to-many relationship. That means every user can have more roles and roles can be set to many users.

User class:

  /**
   * @ORM\Entity
   * @ORM\Table(name="JEP_User")
   * @ORM\Entity(repositoryClass="Chrchel\JepBundle\Repository\UserRepository")
   */
class User implements AdvancedUserInterface {

/**
 * @ORM\Id()
 * @ORM\Column(name="id",type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(name="username",type="string",length=100,unique=true)
 */
private $username;

 /**
 * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
 *
 */
protected $roles;

//....
}

Role class:

/**
 * @ORM\Table(name="JEP_Role")
 * @ORM\Entity()
 */
 class Role implements RoleInterface {

/**
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id()
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

  /** @ORM\Column(name="name", type="string", length=30) */
protected $name;

 /** @ORM\Column(name="role", type="string", length=20, unique=true) */
protected $role;

 /** @ORM\ManyToMany(targetEntity="User", mappedBy="roles") */
protected $users;
 //...
 }

I cant figure how to compose query builder in Symfony2 to list all roles that exists and add it to the end of UserForm where can be selected (as checkboxes) roles granted to the user. I tried to use collection like this in UserType

->add('roles', 'collection',array('label' => 'Role', 'required' => false,'type'=> new RoleType()))

The best I get from symfony are rows with textboxes with selected names of roles. But this is not, what I need.

Answer

gremo picture gremo · Mar 15, 2012

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.