Form alter checkbox which triggers ajax call and show hidden form field

Public

Form alter checkbox which triggers ajax call and show hidden form field. Easy but not so obvious.

Get raw version
php
  1. function module_name_form_alter(&$form, &$form_state, $form_id) {
  2. $form['text_field_name']['und'][0]['value']['#default_value'] = "Default value";
  3. //Hide field
  4. hide($form['text_filed_name']);
  5. //Create a placeholder fieldset
  6. $form['placeholder'] = array(
  7. '#title' => '',
  8. '#prefix' => '<div id="placeholder">',
  9. '#suffix' => '</div>',
  10. '#type' => 'fieldset',
  11. '#description' => '',
  12. '#weight' => 2,
  13. );
  14. //Create a special ajax checkbox
  15. $form['ajax_checkbox'] = array(
  16. '#type' => 'checkbox',
  17. '#title' => t('Fancy ajax checkbox title'),
  18. '#weight' => 1,
  19. '#ajax' => array(
  20. 'callback' => 'ajax_checkbox_callback',
  21. 'wrapper' => 'placeholder',
  22. 'effect' => 'fade',
  23. ),
  24. );
  25. //Checking the special ajax checkbox state
  26. if (!empty($form_state['values']['ajax_checkbox'])
  27. && $form_state['values']['ajax_checkbox']) {
  28. //clear default field value and show the field
  29. $form['text_field_name']['und'][0]['value']['#default_value'] = "";
  30. show($form['text_field_name']);
  31. //move text_field_name to the placeholder
  32. $form['placeholder']['text_field_name'] = $form['text_field_name'];
  33. //remove unused field instance form $form variable
  34. unset($form['text_field_name']);
  35. }
  36. }
  37.  
  38. /**
  39.  * Callback for the ajax special checkbox
  40.  */
  41. function ajax_checkbox_callback($form, $form_state) {
  42. return $form['placeholder'];
  43. }