Symfony 5 : how to add data to a user authenticated in a session, using OneToMany relation?

I want to add data to the strategy table via the title field, and relate it to the user authenticated in a session with the user_id foreign key.

The code below adds data to the strategy table with the relation working, but via a select option (choice_label) coded in my FormType file, listing all the users in my view.

I want to replace that select option by a code which gets the user authenticated in the session instead.

I looked into the Security and Session parts of the documentation, but couldn’t make it work.

My tables :Database

My Controller file:

public function create(Strategy $strategy = null, Request $request, EntityManagerInterface $em)
{
    $strategy = new Strategy();
    
    $form = $this->createForm(StrategyType::class, $strategy);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()){
        $em->persist($strategy);
        $em->flush();
        return $this->redirectToRoute("frStrategy");
    }

    return $this->render('strategy/updateStrategy.html.twig', [
        "strategy" => $strategy,
        "form" => $form->createView()
    ]);

My FormType file:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title')
        ->add('user', EntityType::class,[
            'class' => User::class,
            'choice_label' => 'username'
        ])
    ;
}

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *