AJAX-based dropdown: Select entity, bundle and view mode

Public

</> CopyGet raw version
php
  1. function change_entity_dropdown_form($form, &$form_state) {
  2. $entities = array();
  3. $bundles = array();
  4. $view_modes = array();
  5. foreach (entity_get_info() as $type => $entity) {
  6. $entities[$type] = $entity['label'];
  7. foreach ($entity['bundles'] as $bundle_key => $bundle) {
  8. $bundles[$type][$bundle_key] = $bundle['label'];
  9. }
  10. foreach ($entity['view modes'] as $view_mode_key => $view_mode) {
  11. $view_modes[$type][$view_mode_key] = $view_mode['label'];
  12. }
  13. }
  14. // form items
  15. $selected = isset($form_state['values']['entity']) ? $form_state['values']['entity'] : key($entities);
  16. $form['entity'] = array(
  17. '#type' => 'select',
  18. '#title' => t('Entities'),
  19. '#options' => $entities,
  20. '#default_value' => $selected,
  21. '#ajax' => array(
  22. 'callback' => 'change_entity_dropdown_callback',
  23. ),
  24. );
  25. $form['bundle'] = array(
  26. '#type' => 'select',
  27. '#title' => $entities[$selected] . ' - ' . t('Bundles'),
  28. '#prefix' => '<div id="bundles-select">',
  29. '#suffix' => '</div>',
  30. '#options' => $bundles[$selected],
  31. '#default_value' => isset($form_state['values']['bundle']) ? $form_state['values']['bundle'] : '',
  32. );
  33. $form['view_mode'] = array(
  34. '#type' => 'select',
  35. '#title' => $entities[$selected] . ' - ' . t('View modes'),
  36. '#prefix' => '<div id="view-modes-select">',
  37. '#suffix' => '</div>',
  38. '#options' => $view_modes[$selected],
  39. '#default_value' => isset($form_state['values']['view_mode']) ? $form_state['values']['view_mode'] : '',
  40. );
  41. $form['submit'] = array(
  42. '#type' => 'submit',
  43. '#value' => t('Submit'),
  44. );
  45. return $form;
  46. }
  47.  
  48. function change_entity_dropdown_callback($form, $form_state) {
  49. $commands = array();
  50. $commands[] = ajax_command_replace('#bundles-select', render($form['bundle']));
  51. $commands[] = ajax_command_replace('#view-modes-select', render($form['view_mode']));
  52. return array(
  53. '#type' => 'ajax',
  54. '#commands' => $commands,
  55. );
  56. }