【问题标题】:Symfony 2.7 choice_attr with EntityType fieldSymfony 2.7 choice_attr 与 EntityType 字段
【发布时间】:2016-03-21 07:21:17
【问题描述】:

我需要为 Symfony 2.7 中 EntityType 字段的每个选项添加一个额外的 HTML 属性。

按照this 指南,我假设EntityType 从ChoiceType 继承此功能。我尝试了以下类似的方法,但没有效果;没有 mytype 属性被添加到呈现的选择选项中。

$builder->add('customer_email', 'email')
        ->add('Product', 'entity', array(
              'class' => 'MyBundle:Product',
              'property' => 'name',
              'empty_value' => 'None',
              'required' => false,
              'choice_attr' => function ($val, $key, $index) {
                  return array('mytype' => $val->getType());
              }))

【问题讨论】:

  • 您的选择选项元素没有属性“mytype”?
  • 没错。抱歉,这个问题弄错了;编辑它。

标签: php symfony symfony-forms symfony-2.7


【解决方案1】:

这不一定是最佳答案,但我还不能发布 cmets。

当在 ChoiceType 和 EntityType 上实现choice_attr, choice_labels 等...将被执行。

https://github.com/symfony/symfony/issues/4067

P.S.:进一步调查,确实是继承自ChoiceType,而且只出现在2.7文档中,如果你写类似

'choice_attr' => function (Product $product, $key, $index) {
    return ['class' => $product->getType() ];
}

您应该正确设置类属性,对于我不确定的自定义属性,您可能需要使用'attr' => 'foo'

P.P.S.:经过测试'foo' =>'bar' 可以工作,无需嵌套在“attr”内。

【讨论】:

  • 天啊!你在文档中哪里找到的?我花了几个小时在文档中搜索这个。谢谢!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
  • 2020-10-22
  • 2014-07-27
  • 2018-03-10
  • 2018-09-27
  • 2021-08-09
相关资源
最近更新 更多