Symfony version: 3.1.3 Database: MySQL
I have the users table and it has a column as roles(LongText-DC2Type:array).
In my controller I have
EDIT #2
I looked at my own code, and I gave you the wrong information. Change it to the following. Notice the way you get the role from the form is incorrect, use the below solution. I'm fairly certain this will work for you.
->add('roles', ChoiceType::class, array(
'attr' => array(
'class' => 'form-control',
'style' => 'margin:5px 0;'),
'choices' => array(
'Teacher' => 0,
'Student' => 1,
'Parent' => 2,
),
))
if( $form->isSubmitted() && $form->isValid() ){
// some other codes
$role = $form->get('roles')->getData();
...
@dragoste made a correct statement in that you should have first tried some troubleshooting before posting the question. Also you can search online for answers as well. There are a lot of Symfony examples available.
Your roles values might be directly as keys in your array choices if Users can only have one Role.
'choices' => array(
'Teacher' => ['teacher'],
'Student' => ['student'],
'Parent' => ['parent'],
)
Here is what I did to get rid the issue,
Define Roles in the /app/config/security.yml as below,
role_hierarchy:
ROLE_ADMIN: [ROLE_ADMIN]
ROLE_SUPER_ADMIN: [ROLE_SUPER_ADMIN, ROLE_ALLOWED_TO_SWITCH]
ROLE_TEACHER: [ROLE_TEACHER]
ROLE_STUDENT: [ROLE_STUDENT]
ROLE_PARENT: [ROLE_PARENT]
in the Controller, get the roles from the /app/config/security.yml using the following code
$roles = $this->getParameter('security.role_hierarchy.roles');
and this is the code to roles in the formtype,
$roles = $this->getParent('security.role_hierarchy.roles');
and then in the formtype, (here it is multi select)
->add('roles', ChoiceType::class, array(
'attr' => array('class' => 'form-control',
'style' => 'margin:5px 0;'),
'choices' =>
array
(
'ROLE_ADMIN' => array
(
'Yes' => 'ROLE_ADMIN',
),
'ROLE_TEACHER' => array
(
'Yes' => 'ROLE_TEACHER'
),
'ROLE_STUDENT' => array
(
'Yes' => 'ROLE_STUDENT'
),
'ROLE_PARENT' => array
(
'Yes' => 'ROLE_PARENT'
),
)
,
'multiple' => true,
'required' => true,
)
)
Edit User roles has to be defined in the /app/config/security.yml as below
role_hierarchy:
ROLE_ADMIN: [ROLE_ADMIN]
ROLE_SUPER_ADMIN: [ROLE_SUPER_ADMIN, ROLE_ALLOWED_TO_SWITCH]
ROLE_TEACHER: [ROLE_TEACHER]
ROLE_STUDENT: [ROLE_STUDENT]
ROLE_PARENT: [ROLE_PARENT]