使用 EntityType 构建选择时,如何在 Twig 中设置值? [英] How can I set a value in Twig when the select is built using EntityType?

查看:23
本文介绍了使用 EntityType 构建选择时,如何在 Twig 中设置值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在表单中说我有一个像这样的构建器选项:

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

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

假设我们正在编辑这个选项,在数据库中他们已经选择了plain.使用 Twig,我们可以像这样编写小部件:

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
}) }}

这将使数据库中的值成为选择的预选值.但是如果你对 EntityType 做同样的事情:

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?

推荐答案

为此表单预先选择一个值意味着在基础数据上设置一个值.在你的情况下,控制器应该看起来像:

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()
    ]
}

这篇关于使用 EntityType 构建选择时,如何在 Twig 中设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆