Skip to content
Advertisement

Symfony automatic filling a field of my form by a value from database [closed]

I am using the framework symfony 5 for my website and I have implemented a normal authentication system. I have 2 entities (Users and Patients) and when I enter a new patient through the form, a field of this form must be automatically filled in (and not shown) by the id of the user who has logged in and is making this addition. Who can help me?

The field of my entity that I have to fill is this one: enter image description here

My action in the controller is this one:enter image description here

Advertisement

Answer

No need to put the user id in an input and get it from the client side. Needless to say that the id can be modified by an experienced user ( hiding the input is not a solution).

In your controller you can get the currently authenticated user by using $this-getUser() method or by injecting the SymfonyComponentSecurityCoreSecurity component if your controller is not extending the abstract controller. https://symfony.com/doc/current/security.html#a-fetching-the-user-object

public function new_paziente(Request $request): Response
{
    $paziente = new Paziente();
    $user = $this-getUser();
    $paziente->setResponsabile($user);
    // remaining code unchanged 
    // do not forget to remove the 'responsabile' input from PazienteType and the twig
} 
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement