PM-Riabel PM-Riabel - 2 months ago 27
MySQL Question

Symfony3 how to store user roles in database

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 created a dropdown box for the form as bellow,

$user = new Users;
$form = $this->createFormBuilder($user)
// some other fields
->add('roles', ChoiceType::class, array(
'attr' => array(
'class' => 'form-control',
'style' => 'margin:5px 0;'),
'choices' => array(
'Teacher' => true,
'Student' => true,
'Parent' => true
),
) )
// some other fields
->getForm();


and then I am getting the user selected role as bellow,(within the same controller)

if( $form->isSubmitted() && $form->isValid() ){
// some other codes
$role = $form['roles']->getData();
// some other codes

if( $role == 0 ){
$userRole = array ('teacher');
}
elseif( $role == 1 ){
$userRole = array ('student');
}
elseif( $role == 2 ){
$userRole = array ('parent');
}

$user->addRole($userRole);

$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}


But this gives me the following error,

Expected argument of type "array", "boolean" given


I think I am doing it the wrong way and would like to know the right way to insert roles to the Database.

Answer

Here is what I did to get rid the issue,

get the roles from the /app/config/security.yml using the

$roles = $this->getParameter('security.role_hierarchy.roles');

and then in the form,

->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]
Comments