Drupal - How to add attribute to element in twig before render?

Here is my solution for adding a placeholder to a custom text field being used for inputting search terms in a form. I could not use element.attributes.setAttributes() because in my case the key for attributes is #attributes.

{% set attr = form.search_api_fulltext['#attributes']|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = form.search_api_fulltext|merge({'#attributes': attr}) %}
{{ search }}

Here is the same expanded a little for clarity:

{% set search = form.search_api_fulltext %}   
{% set attr = form.search_api_fulltext['#attributes'] %}
{% set attr = attr|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = search|merge({'#attributes': attr}) %}

{{ search }}

Or add a third merge and merge the field back into the form. Then output the form as usual:

{% set search = form.search_api_fulltext %}
{% set attr = form.search_api_fulltext['#attributes'] %} 
{% set attr = attr|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = search|merge({'#attributes': attr}) %} 

{% set form = form|merge({'search_api_fulltext': search}) %}
{{ form }}

It looks like at this moment this is just not possible. I have created an issue at drupal.org for this. Maybe some day it will get implemented and we can get rid of the phptemplate engine for good.

https://www.drupal.org/node/2567759


Well, I really don't know if you have a particular reason(like keeping everything on the HTML file) to do this in Twig, not in preprocess, but I can give you a code that worked for me on preprocess:

function hook_form_FORM_ID_alter(&$form, &$form_state) {
  $form['actions']['submit']['#attributes']['class'] = array('btn-primary form-control');
}

This code should be in the your_theme.theme file(like the old template.php for Drupal 7).

Tags:

Theming

8