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.
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.
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
))
@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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With