template_preprocess_form_element() does not respect attributes

Created on 14 February 2025, 11 days ago

Problem/Motivation

Working on a custom form, trying to add visibility states to a "item" form element.

The element's html will be rendered without the data-drupal-states attribute.

Steps to reproduce

Drupal 10.4.1
Themes: Seven, Claro, Adminimal, custom

Consider the form below.

When rendered, the text-field element will work as expected, only being visible when selecting the "bar" option.

The markup not so much, even though it has the exact same states it will be rendered without a data-drupal-states attribute and therefore the state api will not pick it up.

namespace Drupal\custom_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class CustomForm extends FormBase {

  public function getFormId() {
    return 'custom_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['options'] = [
      '#type' => 'radios',
      '#title' => $this->t('Choose an option'),
      '#options' => [
        'foo' => $this->t('Foo'),
        'bar' => $this->t('Bar'),
      ],
      '#default_value' => 'foo',
    ];

    $states = [
      'visible' => [
        ':input[name="options"]' => [
          ['value' => 'bar'],
        ],
      ],
      'enabled' => [
        ':input[name="options"]' => [
          ['value' => 'bar'],
        ],
      ],
    ];

    $form['markup'] = [
      '#type' => 'item',
      '#markup' => 'LOREM IPSUM TNANANANANANANANANA',
      '#states' => $states,
    ];

    $form['input'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Text field'),
      '#default_value' => 'test',
      '#states' => $states,
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {}
}

Debugging so far

It seems that template_preprocess_form_element() is erasing the attributes from $variables.

Not sure why this is happening.

Work around

function custom_module_preprocess_form_element(&$variables) {
  if (isset($variables['element']['#attributes']['data-drupal-states'])) { 
    if (!isset($variables['attributes']['data-drupal-states'])) {
      $variables['attributes']['data-drupal-states'] = $variables['element']['#attributes']['data-drupal-states'];
    }
  }
}
🐛 Bug report
Status

Active

Version

10.4

Component

forms system

Created by

🇧🇷Brazil adinancenci

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024