1

I am trying to create a form in Drupal. I want to create the following situation: if a checkbox is selected I want to display a drop down menu. can you please suggest a way to do it.

2
  • Are you developing a custom module or do you need this feature on existing modules like the core node fields or some contrib module?
    – FiNeX
    Aug 19, 2016 at 12:59
  • I needed this in a custom form. I am able to do it now.
    – ana
    Aug 20, 2016 at 5:47

2 Answers 2

2

You can use Drupal form api states.

Example:

function example_form_states($form, &$form_state) {

  $form['click_me'] = array(
    '#type' => 'checkbox',
    '#title' => t('Click me!'),
  );

  $form['example_states'] = array(
    '#type' => 'select',
    '#title' => t('Lorem ipsum dolor sit amet'),
    '#options' => array(
      0 => t('Test 1'),
      1 => t('Test 2'),
     ),
    '#states' => array(
      'visible' => array(
        ':input[name="click_me"]' => array('checked' => TRUE),
      ),
    ),
  );

  return $form;
}

Additional Resources https://api.drupal.org/api/examples/form_example!form_example_states.inc/function/form_example_states_form/7.x-1.x https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x#states

2

Programatic way

  $form['checkbox_form'] = array(
    '#type' => 'checkbox',
    '#title' => t('sometitle'),
    '#default_value' => variable_get('checkbox_form', TRUE),
  );

  $form['selectbox'] = array(
    '#type' => 'select',
    '#title' => t('sometitle'),
    '#default_value' => variable_get('selectbox'),
    '#options' => array(
          TRUE => t('Yes'),
          FALSE => t('No'),
     ),
    '#states' => array(
      'visible' => array(
        ':input[name="checkbox_form"]' => array('checked' => TRUE),
      ),
    ),
  );

Second form element visible makes the trick.

Module Way

Use Conditional Fields module.

Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. A simple use case would be defining a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked, but much more complex options are available.

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.