the_nuts the_nuts - 1 year ago 47
PHP Question

Filter EntityType by owner/current user

I have an EntityType field in a form:


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
- but what is the best way to get the current user inside the form?

Answer Source

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

    class: AppBundle\Form\MyFormType
    arguments: ["@security.token_storage"]
        - { 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();