the_nuts
the_nuts

Reputation: 6054

Filter EntityType by owner/current user

I have an EntityType field in a form:

$builder->add('site')

now all the sites are shown in the dropdown, but I want to show only the ones that belong to the current user.

The app logic is that there are many users, each of them can manage only their own sites (Site::user is a @ORM\ManyToOne(targetEntity="User", inversedBy="sites"))

I know I can use the query_builder - but what is the best way to get the current user inside the form?

Upvotes: 1

Views: 465

Answers (1)

kero
kero

Reputation: 10638

To get the current user object (or id) in the form there are actually multiple ways. One would be to set it via the form's options

$form = $this->createForm(MyFormType::class, $obj, [
    'user' => $this->getUser(),
]);

And enable the option with default value null like so.

class MyFormType extends AbstractType
{

    public function configureOptions(OptionsResolver $resolver)
    {
            $resolver->setDefaults([
                    'data_class' => '...',
                    'user' => null,
            ]);
    }

Now you can use $options['user'] within the buildForm() (make sure to check if it is null or not before using).


But this way you have to always inject the user yourself - why not let Symfony take care of it? First, register your form as a service in services.yml like so

app.form.myform:
    class: AppBundle\Form\MyFormType
    arguments: ["@security.token_storage"]
    tags:
        - { name: form.type }

You see, I already added another thing: the @security.token_storage argument. Now in your form, add a constructor

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class MyFormType extends AbstractType
{

    protected $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
            $this->tokenStorage = $tokenStorage;
    }

And retrieving the user within buildForm() will now be as easy as

$user = $this->tokenStorage->getToken()->getUser();

Upvotes: 2

Related Questions