在表单中说我有一个这样的构建器选项:
->add('choice', ChoiceType::class, [
'choices' => [
'Cheese' => 'cheese',
'Plain' => 'plain
]
])
让我们说我们正在编辑这个选项,在他们已经选择的数据库中。使用twig,我们可以像这样编写小部件:
{{ form_widget(BurgerForm.choice, {
'value': burger.type
}) }}
这将使数据库中的值成为select的预选值。但是如果你用EntityType做同样的事情:
->add('choice', EntityType::class, [
'class' => 'AppBundle:BurgersTypes',
'choice_label' => 'type'
])
并且您使用相同的树枝,它不预先从数据库中选择选项。如何从数据库中获取值以显示为窗口小部件的预选值?
预先选择此表单的值意味着在基础数据上设置值。在您的情况下,控制器应该看起来像:
// 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()
]
}