首页 > 解决方案 > 如何仅使用在 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

标签: symfonysymfony4symfony-1.4

解决方案


您可以像这样使用 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')
    ;

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


推荐阅读