如何仅使用在 Symfony 中具有特定角色的用户填充字段?

How to populate field only with Users who have a certain role in Symfony?

所以我正在开发这个简单的票务管理系统,我有两个实体,User,其中有字段 id, email, roles[] (Admin, Technician or Client),和 username, password, tickets[] (which are all the tickets the client has submitted)。 我有一个 TicketFormType class 允许我创建新票并分配 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_idtable user 中 PK 的 FK,我的问题是作为下拉列表的技术员字段会填充 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')
    ;

您必须根据自己的需要进行调整。