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?
You should try with
pass in the User object to run the query inside the Form
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.
In controller it could look like this:
$this->createForm(SomeFormType::class, $underlyingObjectOrNull, array(
'user' => $this->getUser(),
));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With