Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 3: Passing variables into forms

I'm building using the Symfony 3 Forms, and need to retrieve a collection which is dependant on the current user, within the form to render in a dropdown.

Using the EntityType I can retrieve a list of all entities, but I want to be able to run a custom query which only retrieves those which have a relationship with the current user object.

I've read the documentation on forms and the EntityType, and it explains custom queries and mentions passing in a collection as an argument. But I cannot find instructions on how this is achieved anywhere.

Ideally, I'd like to either pass in a collection I've curated in the Controller, pass in the User object to run the query inside the Form, or otherwise access the user id in the form to run the query on.

Has anyone found a solution to anything similar?

like image 371
Mrshll1001 Avatar asked Dec 24 '22 19:12

Mrshll1001


1 Answers

You should try with

pass in the User object to run the query inside the Form

  1. Define required parameter user in options resolver:

    public function configureOptions(OptionsResolver $resolver)
    {
        // ...
        $resolver->setRequired('user');
        // type validation - User instance or int, you can also pick just one.
        $resolver->setAllowedTypes('user', array(User::class, 'int'));
    }
    

It will force you to pass user option so you won't forget about it.

  1. Pass user instance or user ID as an option into the form.

In controller it could look like this:

$this->createForm(SomeFormType::class, $underlyingObjectOrNull, array(
    'user' => $this->getUser(),
));
  1. Build a custom query for EntityType field:

    $user = $options['user'];
    $builder->add('someField', EntityType::class, array(
        'class' => 'AppBundle:SomeEntity',
        'query_builder' => function (EntityRepository $er) use($user) {
            return $er->createQueryBuilder('u')
               //.. -> some method building the query builder
        },
    ));
    

Please note use($user) part which gives you access to this variable inside anonymous function.

like image 175
Jakub Matczak Avatar answered Dec 26 '22 17:12

Jakub Matczak