Access logged in user in sub Form of a form

30 Views Asked by At

Usually, when I want to access User in a form, I use the Security component. I call it like this :

class OccupantType extends AbstractType
{
    private Security $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

}}}

and use it like this

$builder->add('lease', EntityType::class, [
    'class' => Lease::class,
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('l')
                ->join('l.property', 'p')
                ->join('p.landLords', 'la')
                ->where('la.User = :userId')
                ->setParameter('userId', $this->security->getUser()->getId());
            }
    ]);

But this time I want to do it inside a children form, I call it like this :

->add('multipleLandLords', MultipleLandlordsType::class, [
    'mapped' => false,
])

The file looks like this for now :


namespace App\Form\Type;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use \Symfony\Bundle\SecurityBundle\Security;

class MultipleLandLordsType extends AbstractType
{
    private Security $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('landLords', EntityType::class, [
                'multiple' => true,
                'mapped' => false,
                'class' => LandLord::class,
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('la')
                        ->where('la.User = :userId')
                        ->setParameter('userId', $this->security->getUser()->getId());
                }
            ])
            
        ;
    }
}

My issue is, this time, when used in a sub form, it asks me to hydrate the constructor with the security component instead of loading it automatically like it does on a parent form called with createForm(); How can I access the user from this file then ?

Thank you ! Sorry if I didn't get all the symfony vocabulary right, im quite new to it.

0

There are 0 best solutions below