I'm trying to use "#states". When my checkbox is true, I want to make "required" another field. Drupal prints the "required" asterisk but not correctly.

enter image description here

Here it's the code:

  // Return origin.
  $form['search']['return']['return_ori'] = [
    '#attributes'    => [
      'class'       => ['field-autocomplete', 'ret-ori-name'],
      'data-type'   => 'busstop',
      'placeholder' => t('Write your origin', [], ['context' => 'Backend']),
      'required'    => TRUE,
    '#default_value' => !empty($_GET['return_ori']) ? $_GET['return_ori'] : '',
    '#prefix'        => '<div class="row"><div class="col-md-5">',
    '#states'        => [
      'required' => [
        ':input[name="search_return"]' => [
          'checked' => TRUE,
    '#size'          => 40,
    '#suffix'        => '</div>',
    '#title'         => t('Return origin'),
    '#type'          => 'textfield',
// Return trip.
  $form['search']['search_return'] = [
    '#default_value' => !empty($_GET['search_return']) ? $_GET['search_return'] : FALSE,
    '#prefix'        => '<div class="row"><div class="col-md-5">',
    '#suffix'        => '</div></div>',
    '#title'         => t('Search return trip'),
    '#type'          => 'checkbox',
    '#attributes'    => [
      'class' => ['search-return-trip'],

The submit button has not specific method, so Drupal should handle it. When I press it, the form is sended ignoring my new required field.

Thanks all for help!!

  • Thanks for answer. I've checked but checkbox's name is "search_return". So that is not the problem. I'm not sure about if "#states" only works in web navigator.
    – Javier
    Commented Jul 18, 2018 at 9:45
  • Yes, #states is client side, not server side. You can't use it to validate a required field.
    – Clive
    Commented Jul 18, 2018 at 9:50
  • 2
    The JS form API required/optional states currently do not work at all, only visible / hidden. See Issue on d..o
    – Hudri
    Commented Jul 18, 2018 at 10:25

2 Answers 2


In order to toggle the required state you need to target the widget rather than the form element. Answer courtesy of this very helpful comment on Drupal.org.

In your case the code will be something like:

$form['search']['return']['return_ori']['widget'][0]['value']['#states']= [
  'required' => [
    'input[name="search_return[value]"]' => ['checked' => TRUE],

Check the "name" attribute of your search return checkbox by inspecting it within your browser. You may find the name="" isn't actually name="search_return". It may instead be name="search[search_return]" or something similar. So you need to update your states code to whatever the name is

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.