Symfony2 -> Twig -> Form -> Field -> Set rendered = true

喜夏-厌秋 提交于 2019-12-03 05:38:10

Am I missing the question here? If you want to set a field as rendered even though it is not the simple call is:

{% do form.x.setRendered %}

If I misunderstood, my apologies.

Roman

You can use next closing form statement to prevent rendering form fields which are defined in Form but not described in template:

{{ form_end(form, {'render_rest': false}) }}

For example, we define next form:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add(
            'id',
            HiddenType::class,
            array(                                     
                'required' => false
            )
        )
        ->add(
            'name',
            TextType::class,
            array(                                     
                'required' => false
            )
        )
        ->add(
            'comment',
            TextType::class,
            array(
                'required' => false
            )
        )
        ->add(
            'amount',
            TextType::class,
            array(
                'required' => false
            )
        );
}

For this form we describe next template, but we do not want to render field id, so we can use option render_rest in form_end block to ommit rendering of field id:

{# render opening form tag #}
{{ form_start(form) }}
{# render field with label #}
{{ form_row(form.name) }}
{# render only field #}
{{ form_widget(form.comment) }}
{# render only label #}
{{ form_label(form.amount) }}

{# render only field #}
{{ form_widget(form.amount) }}

{# if csrf token is enabled for form render field #}
{% if form._token is defined %}
{{ form_widget(form._token) }}
{% endif %}

{# render closing form tag and do not render rest form elements #}
{{ form_end(form, {'render_rest': false}) }}

You should remove ( or only add ) the form field in your FormType by including some kind of decision logic.

For example checking for existence/value of a cerain variable.

This variable could then be injected in the constructor.

Removing it from your template is application logic which does not belong into your template.

If have no other choice have a look at the FormView::setRendered() method.

You can access an object's methods using Twigs attribute function:

{{ attribute(object, method, arguments) }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!