【问题标题】:Access properties and methods of a class while configuring EntityType in Formbuilder::add()在 Formbuilder::add() 中配置 EntityType 时访问类的属性和方法
【发布时间】:2016-01-29 13:40:49
【问题描述】:

我的 Symfony2 表单中有一个下拉列表,如下所示:

$builder->add('categories','entity', array(
            'class'     => 'MyBundle:Myentity',
            'property'  => 'name',
            'label'     => 'Mylabel',
            'expanded'  => false,
            'multiple'  => false,
            'label_attr'   =>  array ( 'class'      => 'control-label' ),
            'attr'   =>  array  (   'class'         => 'form-control',
                                    'placeholder'   => 'Placeholder',
                                    'title'         => "Mytitle",
                                    'data-toggle'   => 'tooltip',
                                    'data-myidfromDB'   => '????',
                                    'data-mynamefromDB'=>'????' etc. )));

所以我得到了一个 MyBundle:Myentity 对象的列表,当我选择一个对象时,我想显示它的所有属性(如 ID、名称等),这些属性存储在我的数据库中并在不同的 html 实体类中描述数据-* 字段。如果我从列表中选择另一个,我想在 HTML 中查看与我新选择的选项相关的所有信息(动态更改)。任何想法如何做到这一点?

【问题讨论】:

    标签: php symfony symfony-forms


    【解决方案1】:

    从 Symfony 2.7 开始,您可以将选项 choice_attr 设置为 ChoiceType 并将其设置为可调用,以接收选择作为参数。

    EntityType 继承此选项,在这种情况下选择实例化实体,因此您可以编写如下内容:

    $builder->add('categories','entity', array(
        'class' => 'MyBundle:MyEntity',
        'property' => 'name',
        'label' => 'Mylabel',
        'attr' => array('class' => 'form-control'),
        'label_attr' => array('class' => 'control-label'),
        'choice_attr' => function (\AppBundle\Entity\MyEntity $myEntity) {
            return array(
                'data-private-property' => $entity->getPrivateProperty(),
                'data-some-value' => $entity->someMethod(),
            );
        },
    );
    

    【讨论】:

      【解决方案2】:

      你不能轻易做到这一点。 但是您可以在选择标签中添加更多信息。

      看看 http://symfony.com/doc/current/reference/forms/types/entity.html#choice-label

      您可以在此处输入更多字段详细信息并从您的 javascript 中获取。

      【讨论】:

      • 我尝试使用choice-label,但实际上将下拉列表中的所有选项名称替换为我的数据库中的 ID。事实上,我需要将这些 ID 显示在 HTML 代码中(在选项标签中)。谢谢
      • 您也可以为 entity_widget 创建自己的渲染,并在选项标签中放入更多细节。我认为有可能在 twig 中获取其他字段值。尝试将其转储到 vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig 中的{%- block choice_widget_options -%}
      猜你喜欢
      • 2018-11-07
      • 1970-01-01
      • 2011-07-27
      • 2015-04-25
      • 2010-09-21
      • 2011-08-11
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多