如何将 class 属性设置为具有实体链接属性的 Symfony 表单输入

How to set a class attribute to a Symfony form input with an attribut from entity linked

我的表单中有一个 "beds" 属性,一个链接到另一个 "bedroom" 的实体。 我想为每个输入添加一个 class 和链接实体的 ID "bedroom".

$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                  ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'attr' => array(
        'class' => function ($bed) {
            return $bed->getBedroom()->getId();
        }
     ),
 ))

我有两个问题:

  1. 'attr' => array('class'=>'test) return 包含输入的 div 中的 class 属性,而不是 class 输入中的属性。
  2. 之前的代码无效,returns:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Closure could not be converted to string") in form_div_layout.html.twig at line 358.

感谢您的帮助

  1. 你需要customize form rendering
  2. 前面的代码不起作用,因为您试图传递 Closure 对象而不是字符串值。 attr 数组用作字段属性,因此它必须仅包含字符串值(或具有 __toString() 方法的对象)。

我看到您正在使用复选框。 您的代码似乎没问题,并且由于您使用 query_builder,因此值应该是 Bed Entity。请注意 EntityType documentation 中未提及 attr,我认为您需要改用 choice_attr

你能试试这个吗?我不确定它是否有效:

$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                    ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'choice_attr' => function ($val) {
            return ['class' => $val->getId()];
    },
))

让我们知道结果。

对于 EntityType,它看起来像这样:

$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                    ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'choice_attr' => function (Bed $bed, $key, $index) {
            return ['class' => $bed->getBedroom()->getId();];
    },
))

由于 choice_attr 似乎不再有效,我正在编写另一个解决方案。我无法直接从 formBuilder 设置属性(确切地说 "min")。我设法在js的帮助下添加了它。我只是通过 formBuilder 给出的 ID 搜索元素并添加了属性。

在浏览器元素检查器中检查您的表单并找到 ID。

<div id="form_deadLine">
   <input type="date" id="form_deadLine_date" name="form[deadLine][date]" required="required" value="2020-02-20"/>
</div>

你想找我的情况是form_deadLine_date。

然后你想将 .js 文件连接到你的 twig 模板并在那里编写简单的脚本。

const form = document.getElementById('form_deadLine_date');
if(form){
    form.setAttribute("min", "2020-01-02")
}

那么我的代码如下所示:

<div id="form_deadLine">
   <input type="date" id="form_deadLine_date" name="form[deadLine][date]" required="required" value="2020-02-20"/>
</div>