1

I come from read this Using the Drupal 7 Form API states system to create conditions between form elements and I'm able to use the #states with an input element like the title (textfield element), the problem is that if I try to use a container element the #states doesn't works.

This code works:

$form['field_courriels_des_autres']['#states']['disabled']['input[name="title"]']['filled'] = TRUE;

This code doesn' works:

$form['field_preciser']['#states']['enabled']['select[name="field_salle"]']['value'] = 'other';

I think that the problem is that the field_salle is a container.

enter image description here

3
  • It doesn't work for fieldsets (known core issue), it's probably the same for containers
    – Clive
    Apr 18 '16 at 15:27
  • @clive any clues to solve this? Apr 18 '16 at 15:28
  • 1
    IIRC, I gave up about an hour into trying the various (broken) batches available to fix it. I think I went with some custom JS in the end
    – Clive
    Apr 18 '16 at 15:30
1

As it's been mentioned, the #states property doesn't work for fieldsets, containers. You need some JS here, e.g:

The form

$form['promo_code_trigger'] = [
  '#type' => 'container',
  '#attributes' => ['id' => ['promo-code-add-el']],
  'data' => [
    '#markup' => t('Add promotional code'),
  ]
];

$form['promo_code_wrapper'] = [
  '#type' => 'container',
  '#attributes' => [
    'id' => ['promo-code-add-el-triggered'],
    'class' => ['hidden'],
  ],
];

JS

$("#promo-code-add-el").on("click", function (e) {
  $('#' + e.target.id + "-triggered").toggleClass('hidden');
  $('#' + e.target.id).toggleClass('active');
});
2

States indeed doesn't work with containers yet, because containers don't have necessary wrapper classes (.js-form-item or .js-form-wrapper). However you can do a workaround to get #states API to work with containers. Here is working code example from Drupal 9:

$form['container'] = [
  '#prefix' => '<div class="js-form-wrapper">',
  '#suffix' => '</div>',
  '#type' => 'container',
  '#states' => [
    'visible' => [
      ':input[name="field_name"]' => ['value' => 'your_conditional_value_here'],
    ],
  ],
];

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.