Symfony3 how to store user roles in database

后端 未结 3 1620
余生分开走
余生分开走 2020-12-12 07:01

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

3条回答
  •  無奈伤痛
    2020-12-12 07:18

    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]
    

提交回复
热议问题