symfony2 form multiple select with arraycollection

lordjancso picture lordjancso · May 9, 2013 · Viewed 20.3k times · Source

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.

Answer

redbirdo picture redbirdo · May 10, 2013

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.