I have a node with a field, whose widget uses select boxes and multiple choices are possible. The values are coming from a taxonomy entity reference field. There is another field, a text field, which needs to be hidden.

 * Implements hook_form_alter().
function mijn_condities_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if($form_id == 'node_bedrijf_form' || $form_id == 'node_bedrijf_edit_form'){
    $form['field_afstand']['#states'] = array(
      'visible' => array(
        ':input[name="field_openbaar_vervoer"]' => array('value' => '236'),

A select box should be added according their choice. For example, when they choose bus or tram, there should be a field to enter the distance in meters. When they choose airport, the range must be in kilometers.

The field isn't hiding. I already tried to make the field invisible, but this doesn't work.

Does anyone know what is wrong?

1 Answer 1


This is a little bit tricky the Form API #states works with jQuery selectors if your filed field_openbaar_vervoer coming from a taxonomy entity reference.
So the input generated HTML will be something like (example from tags fields)

<input data-drupal-selector="edit-field-tags-3" aria-describedby="edit-field-tags--description" type="checkbox" id="edit-field-tags-3" name="field_tags[3]" value="3" class="form-checkbox">

So to target all those inputs you should use Starts With Selector in your code and it will work:

$form['field_afstand']['#states'] = [
  'visible' => [
    ':input[name^="field_openbaar_vervoer"]' => ['value' => '236'],

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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