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'
])
;
}
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()],
])
;
}
Thanks a million time, your solution worked. You can even remove the 'choice_label' => 'username' since as you said, it's not relevant. I am new to stackoverflow, can I do something else besides marking your answer as positive to thank you ?
Upvoting the answer if you can with your level, if you can't that's is fine, glad to help ;)
Thank you. One more thing, I am trying to get rid of the select in my view caused by the 'choices' option. I tried to use a HiddenType::class with the 'data' option, but I couldn't make it work (error : Expected argument of type "App\Entity\User or null", "string" given at property path "user". ). Which form type and option could I use instead of EntityType and choices, to get the user authenticated without rendering it in my view ?