Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 form multiple select with arraycollection

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.

like image 497
lordjancso Avatar asked Oct 16 '25 03:10

lordjancso


2 Answers

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.

like image 142
redbirdo Avatar answered Oct 17 '25 16:10

redbirdo


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
    ));
like image 32
stwe Avatar answered Oct 17 '25 16:10

stwe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!