Search code examples
symfonysymfony4symfony-1.4

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


So I'm working on this simple ticket management system, I have two entities, User which has fields id, email, roles[] (Admin, Technician or Client), and username, password, tickets[] (which are all the tickets the client has submitted). I Have a TicketFormType class that allows me to create new tickets and assign a technician to that ticket, here is the code for it:

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')
    ;
}

Now in my db structure, I have ticket table that has these fields id technician_id customer_id title priority body assignment_date where technician_id is a FK to a PK intable user, my problem is that the technician field which is a dropdown gets populated with all users of User table including those who don't have ROLE_TECHNICIAN. How do I solve this?

NOTE: I store all technicians, clients, admins in table Users

Solution

  • You could use a QueryBuilder like so:

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

    You'll have to adapt this to your needs.