gpt4 book ai didi

php - Symfony3如何在数据库中存储用户角色

转载 作者:行者123 更新时间:2023-11-29 11:19:21 25 4
gpt4 key购买 nike

Symfony 版本:3.1.3数据库:MySQL

我有用户表,其中有一列为角色(LongText-DC2Type:array)。

在我的 Controller 中,我为如下形式创建了一个下拉框,

$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();

然后我得到用户选择的角色,如下所示,(在同一 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();
}

但这给了我以下错误,

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

我认为我的做法是错误的,并且想知道将角色插入数据库的正确方法。

最佳答案

这是我为解决这个问题所做的事情,

在/app/config/security.yml 中定义角色,如下所示,

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]

在 Controller 中,使用以下代码从/app/config/security.yml 获取角色

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

这是表单类型中角色的代码,

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

然后在formtype中,(这里是多选)

->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,
)
)

编辑用户角色必须在/app/config/security.yml 中定义,如下

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]

关于php - Symfony3如何在数据库中存储用户角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39198846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com