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 Answers
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
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.