Search code examples
formstwigdrupal-8

How to remove a field in the form twig in Drupal 8?


In Drupal 8, the form twig is like that :

<form{{ attributes }}>
  {{ children }}
</form>

I would like display all fields exept one. Usually we use the without filter but children is a string so that won't work.

<form{{ attributes }}>
  {{ children|without('unwanted') }}
</form>

In the form twig, we can access to the element variable which is an array. But still, the without filter doesn't work here.

<form{{ attributes }}>
 {{ element|without('unwanted') }}
</form>

I know I can display all the fields 1 by 1 with {{ element.field }}, But if my form has new fields they will not be printed until I update the form twig. I want to keep the dynamical purpose.

I do not want to update the form code in php to keep the layout in twig.

Any idea ?


Solution

  • We found a quite good answer :

    1. Create the custom template
    {#
    /**
     * @file
     *
     * Available variables
     * - form
     *
     * @see template_preprocess_mycustomform()
     *
     * @ingroup themeable
     */
    #}
    {{ form }}
    
    1. Declare the template in the theme function
    'mycustomform' => [
      'render element' => 'form',
    ],
    
    1. Apply the template to the form
    $form['#theme'] = 'mycustomform';
    

    Result : In the new template, we can use the without twig function

    {{ form|without('myfield') }}
    

    Edit 2023

    Maybe a simpler solution :

        <div class="fr-mb-2w">
          <div class="fr-grid-row  fr-grid-row--gutters">
            <div class="fr-col fr-col-md-6">{{ element.email }}</div>
            <div class="fr-col fr-col-md-6">{{ element.profile }}</div>
          </div>
        </div>
    
        {# Display all other fields. #}
        {% for name in element|keys %}
          {% if not (name starts with '#' or name in ['email', 'profile', 'actions']) %}
            {{ element[name] }}
          {% endif %}
        {% endfor %}