【问题标题】:Symfony3: pass value to Form EntityType be the default selected valueSymfony3:将值传递给 Form EntityType 作为默认选择值
【发布时间】:2016-07-13 01:39:20
【问题描述】:

我有一个表单,应该允许将项目(device)添加到类别(brand)。下面是创建表单的控制器的一部分($brand 不起作用,但我稍后会弄清楚)。下面是创建我的表单的代码。

我希望我的选择框(它是 Brand 的实体类型,并显示所有可能的品牌)也根据传递的变量显示默认 selected 值由控制器。

两个问题:

  1. 我可以在哪里传递这个值?
  2. 如何为 EntityType 选择框设置默认选项?我希望它是“数据”,但即使对数字进行硬编码也行不通。

这是控制器位:

public function createDevice(Request $request, $brand) {
    $device = new Device();
    $form = $this->createForm(DeviceType::class, $device); // where do I pass the value of the default option?
    $form->handleRequest($request);

类型

class DeviceType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder
            ->add('brand', EntityType::class, array(
                'class' => 'AppBundle:Brand',
                'choice_label' => 'name',
                'choice_value' => 'id',
                'data' => '2' // does not set default value to second item!

【问题讨论】:

  • 嗨,在您上面的代码中,您不能通过 TWIG 将 $brand 作为对象传递;但你可以通过控制器。只是想帮助你。如果它是品牌 ID,那么您可以在查询构建器中使用它。
  • 不确定您的意思?我想我不是想把物体传递给树枝。我对这一切有点陌生:)
  • 您好,bluppfisk。你有函数代码:createDevice(Request $request, $brand),变量$brand。您是否尝试将品牌对象传递给函数?如果是这样,它需要是一个对象。

标签: forms symfony


【解决方案1】:

只需将品牌设置为设备。

$em = $this->getDoctrine()->getManager();
$brand = $em->getRepository('AppBundle:Brand')->find(2);
$device = new Device();
$device->setBrand($brand);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多