guowy
guowy

Reputation: 257

Symfony User Roles not selected in user form

I have created a simple user/role form. The form shows the user's detail correctly and displays all the possible roles, but for some reason it does not pre-select the users' current role. For the relationship between the user and role I had the following in the user entity class:

/** 
* @ORM\ManyToMany(targetEntity="Role", inversedBy="users", cascade={"persist","remove"}) 
* @ORM\JoinTable(name="user_role") 
*/ 
protected $roles;

The formtype class was built using:

$builder->add('firstname')
->add('lastname')
->add('email')
->add('roles');

The database looks like this: enter image description here

Any hints/assistance would be appreciated.

Upvotes: 1

Views: 1039

Answers (2)

Fazhom Arnaud
Fazhom Arnaud

Reputation: 61

Had the same problem in symfony4, adding this did the trick for me:

'choice_value' => function ($choice) {
    return $choice;
},

Upvotes: 0

vardius
vardius

Reputation: 6546

You need to define your roles fields as entity http://symfony.com/doc/current/reference/forms/types/entity.html change this line ->add('roles'); to:

->add('roles', 'entity', array(
                'multiple' => true,
                'expanded' => true,
                'property' => 'name',
                'class'    => 'Your_Path\Entity\Roles',
        ));

it should work.

Second option:

you can try to create role type form as mentioned here and then do something like this

$builder->add('roles', 'collection', array('type' => new RoleType()));

its recomended to read this this about mapped option and other as by_reference

Upvotes: 3

Related Questions