0

In a Form say I have a builder option like this:

->add('choice', ChoiceType::class, [
   'choices' => [
       'Cheese' => 'cheese',
       'Plain' => 'plain
     ]
])

And let's say we are editing this option, in the database they've already selected plain. With twig we can write the widget like this:

{{ form_widget(BurgerForm.choice, {
  'value': burger.type
}) }}

This will make the value in the database the pre-selected value for the select. But if you do the same thing with EntityType:

->add('choice', EntityType::class, [
   'class' => 'AppBundle:BurgersTypes',
   'choice_label' => 'type'
])

And you use the same twig it doesn't pre-select the option from the database. How can I get the value from the database to show as the pre-selected value of the widget?

1 Answers1

0

Pre-selecting a value for this form means setting a value on the underlying data. In your case, the controller ought to look something like:

// src/AppBundle/Controller/MyController.php

namespace AppBundle\Controller\MyController;

use AppBundle\Entity\Order;
use AppBundle\Entity\BurgersTypes;
use AppBundle\Form\Type\FormType;
use Symfony\Component\HttpFoundation\Request;

public function formAction(Request $request)
{
    $obj = new Order();
    $defaultBurgerChoice = new BurgersTypes('cheese');
    $ob->setChoice($defaultBurgerChoice);
    $form = $this->create(FormType::class, $obj);

    $form->handleRequest($request);

    ...

    // Now, if the form needs to render a value for `choice`, 
    // it will have the value of BurgerForm.choice  determined
    // intentionally - by your default, or overridden and 
    // handled in the request!
    return [
        'BurgerForm' => $form->createView()
    ]
}
Cameron Hurd
  • 4,836
  • 1
  • 22
  • 31