For a choice of entities you should use the special choice field type 'entity' (see Symfony manual for entity field type). For an example see my answer to a similar question. If you get further errors you may also find this question on Role Interface and Manage Roles helpful.
symfony2 form multiple select with arraycollection
-
21-04-2022 - |
Question
I would like to create a form to edit my users.
Users and roles connected with ManyToMany.
In UserUsers entity I have a $roles variable which is ArrayCollection
:
public function __construct()
{
$this->roles = new ArrayCollection();
}
On my form I would like to add roles to my users via multiple select form element. In my user form:
public function buildForm( FormBuilderInterface $builder, array $options ) {
$builder->add( 'username' )
->add( 'password', 'repeated', array(
'type' => 'password',
'mapped' => false,
'required' => false,
'first_options' => array(
'label' => 'Password' ),
'second_options' => array(
'label' => 'Repeat Password' ) ) )
->add( 'roles', 'choice', array(
'mapped' => false,
'multiple' => true ) );
}
Now my multiple select is empty.
If I turn mapped to true, I got an error message:
UserRoles could not be converted to int in...
I've tried a lots of ways, but I could not solve this problem correctly.
Solution
OTHER TIPS
for the fosuserbundle I do it like that:
$builder->add('roles', 'choice', array(
'multiple' => true,
'choices' => array(
'ROLE_USER' => 'User',
'ROLE_AUTHOR' => 'Autor',
'ROLE_MODERATOR' => 'Moderator',
'ROLE_ADMIN' => 'Admin'
),
'label' => 'Rollen',
'required' => true
));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow