代码之家  ›  专栏  ›  技术社区  ›  Kim

Symfony ChoiceType深度标签定制

  •  1
  • Kim  · 技术社区  · 7 年前

    我想高度定制EntityType的选项标签,比如创建一个包含模型多个属性的表。

    MyClass 通过 EntityType . 我怎样才能在细枝上这样做?

    1. json_encode

    2. 在我的模板中,我 json_decode

    代码:

    1.

    $builder
        ->add('field', EntityType::class, [
            'class' => MyClass::class,
            'multiple' => false,
            'expanded' => true,
            ],
            'choice_label' => function (MyClass $myClass) {
                $data = [
                    'name' => $myClass->getName(),
                    'description' => $myClass->getDescription(),
                ];
    
                return json_encode($data);
            },
        ])
    

    {% block my_form_widget %}
        ...
        {# form is my 'field' FormView of the EntityType #}
    
        {% for child in form %}
            {# child is a FormView, one choice of my EntityType #}
            {# child.vars.data is boolean as its a checkbox #}
    
            {% set data = child.vars.label|json_decode %}
            create some complex html here, like tables
            ...
        {% endfor %}
    ...
    {% endblock %}
    

    工作但是有更好的办法吗?

    基姆

    2 回复  |  直到 7 年前
        1
  •  0
  •   futureal    7 年前

    在映射到实体的Symfony表单(或表单字段,它只是它自己的一个表单)中,您始终可以访问中的底层数据 form.vars.data form.vars.data 要么是 null MyClass .

    为便于在模板中使用,您可以执行以下操作:

    {% set my_object = form.field.vars.data %}
    {% if my_object %}
        {{ my_object.getName() }}
        {{ my_object.getDescription() }}
    {% endif %}
    

    因此,不需要为视图层重新编码实体数据,因为它总是可用的。

    如果您与一个 EntityType choices 数组:

    {% for choice in form.field.vars.choices %}
        {{ choice.data.getName() }}
        {{ choice.data.getDescription() }}
    {% endfor %}
    

    {{ dump(form.field) }}
    

    这将允许您查看可用数据,并查看所有可用数据。注意,它需要启用Twig调试扩展,并在PHP中启用XDebug,以使输出看起来更漂亮。

        2
  •  0
  •   Kim    7 年前

    好的,我知道了,下面是一个如何在twig中访问EntityType选择的数据的示例。你可以查一下 child.parent.vars.choices 列表

    {% block my_form_widget %}
        ...
        {# form is my 'field' FormView of the EntityType #}
    
        {% for child in form %}
            {# child is a FormView, one choice of my EntityType #}
            {# child.vars.data is boolean as its a checkbox #}
    
            {% for choice in child.parent.vars.choices if choice.value == child.vars.value %}
    
                {{ choice.data.name }} {# contains MyClass name #}
                {{ choice.data.description }} {# contains MyClass description #} 
    
            {% endfor %}
            ...
        {% endfor %}
    ...
    {% endblock %}