使用EntityType构建选择时,如何在树枝中设置一个值



在表格中说我有这样的构建器选项:

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

,假设我们正在编辑此选项,在他们已经选择的数据库中。使用树枝,我们可以写这样的小部件:

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

这将使数据库中的值成为选择的预选值。但是,如果您使用EntityType做同样的事情:

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

您使用相同的树枝,它不会从数据库中预选选项。如何从数据库中获取值以显示为小部件的预选值?

预选此表格的值意味着在基础数据上设置值。在您的情况下,控制器应该看起来像:

// src/AppBundle/Controller/MyController.php
namespace AppBundleControllerMyController;
use AppBundleEntityOrder;
use AppBundleEntityBurgersTypes;
use AppBundleFormTypeFormType;
use SymfonyComponentHttpFoundationRequest;
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()
    ]
}

最新更新