Skip to content

Instantly share code, notes, and snippets.

@davereid
Created May 3, 2011 22:18
Show Gist options
  • Save davereid/954384 to your computer and use it in GitHub Desktop.
Save davereid/954384 to your computer and use it in GitHub Desktop.
Drupal 7: Entity and bundle select fields with AJAX dependent dropdown
<?php
function entity_bundle_ajax_form() {
$form['entity_type'] = array(
'#type' => 'select',
'#title' => t('Entity type'),
'#options' => array('' => t('- Select one - ')),
'#default_value' => '',
'#ajax' => array(
'callback' => 'entity_bundle_ajax_form_callback',
'wrapper' => 'bundle-select',
//'method' defaults to replaceWith, but valid values also include
// append, prepend, before and after.
// 'method' => 'replaceWith',
// 'effect' defaults to none. Other valid values are 'fade' and 'slide'.
// See ajax_example_autotextfields for an example of 'fade'.
//'effect' => 'slide',
// 'speed' defaults to 'slow'. You can also use 'fast'
// or a number of milliseconds for the animation to last.
// 'speed' => 'slow',
// Don't show any throbber...
'progress' => array('type' => 'none'),
),
'#required' => TRUE,
);
$form['bundle'] = array(
'#type' => 'select',
'#title' => t('Bundle'),
'#options' => array(),
//'#default_value' => '',
'#prefix' => '<div id="bundle-select">',
'#suffix' => '</div>',
'#bundles' => array(),
'#required' => TRUE,
'#states' => array(
'invisible' => array(
':input[name=entity_type]' => array('value' => ''),
),
),
);
foreach (entity_get_info() as $entity_type => $entity_info) {
$form['entity_type']['#options'][$entity_type] = $entity_info['label'];
foreach ($entity_info['bundles'] as $bundle_key => $bundle_info) {
$form['bundle']['#bundles'][$entity_type][$bundle_key] = $bundle_info['label'];
}
}
}
function entity_bundle_ajax_form_callback($form, $form_state) {
$entity_type = $form_state['values']['entity_type'];
$form['bundle']['#options'] = $form['bundle']['#bundles'][$entity_type];
if (count($form['bundle']['#options']) === 1) {
$form['bundle']['#default_value'] = key($form['bundle']['#bundles'][$entity_type]);
}
else {
}
return $form['bundle'];
}
@nevergone
Copy link

"An illegal choice has been detected. Please contact the site administrator." :(

@nevergone
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment