2

We want to customize the theme of our webforms. We will want the ability to add markup around individual webform elements (like my_element_01 and my_element_02 in the example below)

Below is a very basic twig template that seems like the right path (based a little on How to access webform elements in webform.html.twig ). However, when I submit this form I get "The form has become outdated. Copy any unsaved work in the form below and then reload this page.".

I have read that the form_id and form_build_id has to be rendered in the template but I am doing that. I am not sure what is wrong or if there is a better approach.

{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_01 }}

  {{ element.form_build_id }}
  {{ element.form_id }}
  {{ element.actions }}

{{ title_suffix }}

</form>
3

The issue was I was not rendering out the {{ element.form_token }} element. I added that element and it works:

{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_02 }}

  {{ element.form_build_id }}
  {{ element.form_id }}
  {{ element.form_token }}
  {{ element.actions }}

{{ title_suffix }}

</form>

This works which is why I submitted it as an answer. I do think it could be better written. This would require effectively using the twig 'without' filter which I can't get to work. I am creating a separate post about that as I feel they are different topics. The basic idea is I shouldn't have to fish or remember to render all the items that make up a drupal form such as form_build_id, form_id, form_token, or actions. I should render the entire element array and hide the fields I want to wrap in markup. Then I can explicitly render those fields. Something like:

{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element|without('elements) }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_02 }}

{{ title_suffix }}

</form>

But that currently renders my_element_01 and my_element_02 twice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.