- Issue created by @adinancenci
- 🇧🇷Brazil adinancenci
So turned out that the problem was that I was using #markup instead of #description.
Now it woks...
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.
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) {}
}
It seems that template_preprocess_form_element()
is erasing the attributes from $variables
.
Not sure why this is happening.
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'];
}
}
}
Active
10.4 ✨
forms system
So turned out that the problem was that I was using #markup instead of #description.
Now it woks...