Symfony表单覆盖字段外观

时间:2016-04-20 11:27:32

标签: php forms symfony symfony-forms

我试图覆盖现场外观。

我创建了自定义表单类型:

namespace AppBundle\Form\Type\Frontend\Search;

/**/

class TripTypeType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'choices'     => [
                'One-way',
                'Round-trip',
            ],
            'multiple'    => false,
            'expanded'    => true,
            'required'    => false,
            'empty_value' => false,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return ChoiceType::class;
    }
}

之后我将此字段添加到父表单:

namespace AppBundle\Form\Type\Frontend\Search;

/***/

class FlightSearchType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('tripType', TripTypeType::class)
            ->add('airports', AirportsType::class)
            ->add('flightAt', FlightDatesType::class)
            ->add('flightClass', FlightClassType::class);
    }
}

然后像这样渲染这个字段:

{% for type in form.tripType %}
    {% if loop.index == 1 %}
        {% set way_id = 'one-way' %}
    {% else %}
        {% set way_id = 'round-trip' %}
    {% endif %}

    {{ form_widget(type, {
        'id': way_id,
        'attr': {'class': 'tabs-way__radio'},
        'label_attr': {'class': 'tabs-way__label', 'for': way_id}
    }) }}
{% endfor %}

所以我想得到的是:

<div class="tabs-way__item">
    <input type="radio" id="one-way" name="flight_search[tripType]" class="tabs-way__radio" value="0">
    <label class="tabs-way__label" for="one-way">One-way</label>
</div>

为此,我试图覆盖此字段的小部件:

{# app/Resources/views/Form/fields.html.twig #}
{% block trip_type_widget %}
    <div class="tabs-way__item">
        <input type="radio" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
        {{ block('form_label') }}
    </div>
{% endblock trip_type_widget %}

我将该文件包含在config.yml的树枝部分中。但我得到的一切都没有:(

1 个答案:

答案 0 :(得分:0)

如果您需要覆盖自定义字段,则必须prefix it with underscore,例如:

{% block _trip_type_widget %}
    <div class="tabs-way__item">
        {{- form_label(form) -}}
        {{- form_widget(form) -}}
        {{- form_errors(form) -}}
    </div>
{% endblock _trip_type_widget %}