PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 20, 2022

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

 January 20, 2022     foreign-keys, session, symfony     No comments   

Issue

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'
        ])
    ;
}

Solution

Either pass the current user to form in an option or inject the security component in the form and use it from there. I think it kinda weird to put a select if you know you'll always have only one option in it but that's another subject.

private $security;

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

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


Answered By - Julien B.
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing