Symfony 5 How to create a form using parameter converter as value for one of the field

I made a form that works with two tables joined (OneToMany, a strategy can have many strenghts), but I could only make it work with ‘choice_label’ for the ‘strategy’ field, as shown below.

Instead of the ‘choice_label’ which gives the user a list of strategies to choose from by titles, I want my code to retrieve the value of the parameter converter {title} used in my controller functions to identify which strategy is wanted, so that when the form is filled and sent, it automatically sets the strenght to the right strategy.

I looked into the many FormType Field of the documentation, and tried option like ‘data’ instead of ‘choice_label’ but couldn’t make it work. Thank you for your help !

My FormType file :

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

My Controller file :

/**
 * @Route("fr/strategy/content/{title}", name="frContentStrategy")
 */
public function index(Strategy $strategy): Response
{
    return $this->render('content_strategy/contentStrategy.html.twig', [
        "strategy" => $strategy
    ]);
}

/**
 * @Route("fr/strategy/content/{title}/createforce", name="frCreateForce")
 * @Route("/fr/strategy/content/{title}", name="frUpdateForce", methods="GET|POST")
 */
public function createUpdate(DiagnosticForce $diagnosticforce = null, Request $request, EntityManagerInterface $em)
{
    if(!$diagnosticforce){
        $diagnosticforce = new DiagnosticForce();
    }
    $form = $this->createForm(DiagnosticForceType::class, $diagnosticforce);
    $form->handleRequest($request);

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

    return $this->render('content_strategy/createForce.html.twig', [
        "diagnosticforce" => $diagnosticforce,
        "form" => $form->createView()
    ]);
}

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

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