symfony - 如何仅使用在 Symfony 中具有特定角色的用户填充字段?
问题描述
所以我正在研究这个简单的票务管理系统,我有两个实体,User
分别有字段id, email, roles[] (Admin, Technician or Client)
和username, password, tickets[] (which are all the tickets the client has submitted)
. 我有一TicketFormType
门课,可以让我创建新票并分配a technician to that ticket
,这是它的代码:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class, [
'label' => 'Title',
'attr' => ['placeholder' => 'Ticket title']
])
->add('priority', ChoiceType::class, [
'multiple' => false,
'choices' => [
'Very High' => 5,
'High' => 4,
'Medium' => 3,
'Low' => 2,
'Very Low' => 1
]
])
->add('body')
->add('assignmentDate')
->add('technician') // this field gets populated with all users including those who don't have ROLE_TECHNICIAN
->add('customer')
;
}
现在在我的数据库结构中,我有ticket table
这些字段id technician_id customer_id title priority body assignment_date
,其中technician_id
一个 FK 到一个 PK table user
,我的问题是,作为下拉列表的技术人员字段填充了所有用户,User table
包括那些没有的用户ROLE_TECHNICIAN
。我该如何解决这个问题?
NOTE: I store all technicians, clients, admins in table Users
解决方案
您可以像这样使用 QueryBuilder:
$builder
->add('title', TextType::class, [
'label' => 'Title',
'attr' => ['placeholder' => 'Ticket title']
])
->add('priority', ChoiceType::class, [
'multiple' => false,
'choices' => [
'Very High' => 5,
'High' => 4,
'Medium' => 3,
'Low' => 2,
'Very Low' => 1
]
])
->add('body')
->add('assignmentDate')
->add('technician') // this field gets populated with all users including those who don't have ROLE_TECHNICIAN
->add('technician', EntityType::class, [
'class' => User::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->andWhere('u.ROLE LIKE :role')
->setParameter('role', '%\'ROLE_TECHNICIAN\'%');
},
'choice_label' => 'username',
])
->add('customer')
;
您必须根据自己的需要进行调整。
推荐阅读
- excel - 使用vba获取excel列中的所有唯一值
- android - 如何阻止 GSON 在 Android 中自动投射
- terminology - “低礼”是什么意思?
- java - 叠加图像
- matlab-cvst - Matlab Simulink 中要阻止的输入
- c++ - 为什么即使在使用减量运算符后,while 循环内的数组也会出现越界错误?
- javascript - 谷歌地图地理编码器没有给我结果
- python - 有没有办法在 python 中等待用户输入一段时间后暂停脚本?
- python - Django:如何从 POST 请求创建模型?
- node.js - 将 docx 文件上传到 Firebase 存储后获取带有访问代码的文件 URL