6

I've got one radios element:

$form['trip_radios'] = array(
  '#type' => 'radios',
  '#options' => array(
    'new' => t('Create a new trip'),
    'existing' => t('Use an existing trip'),
  )
);

I've got some #states prepared:

$trip_states = array(
  'visible' => array(
    ':input[name="trip_radios"]' => array(
      'value' => 'new'
    )
  )
);

And some other elements that use $trip_states for their #states:

$form['itinerary_radios'] = array(
  '#type' => 'radios',
  '#options' => array(
    'new' => t('Create a new itinerary'),
    'existing' => t('Use an existing itinerary'),
  ),
  '#states' => $trip_states
);

$form['title'] = array(
  '#type' => 'textfield',
  '#title' => 'Itinerary name',
  '#required' => FALSE,
  '#states' => $trip_states
);

The title form element (and many others) properly listens to the #states condition and works just fine. However, itinerary_radios always shows up no matter what (if anything) is checked on trip_radios. Why does a visible condition on a radios element's #states not listen to another radios value?

1 Answer 1

6

In misc/states.js, it looks for the closest form-item, form-submit, or form-wrapper. Here's the line:

$(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value);

This does not play well with the way radios are themed, and states.js does not find anything to toggle. Wrapping the itinerary_name radios in a container and applying #states to the container item is what I would call the quickest workaround.

$form['itinerary_radios'] = array(
  '#type' => 'container',
  '#attributes' => array(),
  'radios' => array(
    '#type' => 'radios',
    '#options' => array(
      'new' => t('Create a new itinerary'),
      'existing' => t('Use an existing itinerary'),
    ),
  ),
  '#states' => $trip_states
);
2
  • Will it work in a text field? Sep 1, 2015 at 3:16
  • I guess another option is to set '#tree' => TRUE on a wrapping #type => 'container' or fieldset.
    – leymannx
    Aug 25, 2017 at 8:44

Your Answer

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

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