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.
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.