Dynamic form using FAPI

Public

I was trying to code a calculator using the FAPI, but I was having trouble understanding how to replace parts of the form with dynamic output. This is what I ultimately produced, and I would welcome any feedback.

The function FORM_NAME_form actually produces and outputs the form renderable array. To output the form, use `$form = drupal_get_form($form_id); print drupal_render($form);`. Alternatively, you can display the form as a separate page using hook_menu. Set `'page callback' => 'drupal_get_form', 'page arguments' => array('FORM_NAME_form')` (see the hook_menu function page for details).

</> CopyGet raw version
php
  1. <?php
  2. /**
  3.  * This function defines our form, returning a renderable array for the form.
  4.  */
  5. function FORM_NAME_form($form, &$form_state) {
  6. // Add a form input to take a value. The form input makes an AJAX call back
  7. // to the server when the value is changed and replaces the DOM element
  8. // #FORM_NAME_output with output from the PHP function
  9. // _FORM_NAME_generate_output
  10. $form['x'] = array(
  11. '#type' => 'textfield',
  12. '#title' => t('Enter a Number'),
  13. '#default_value' => '100000',
  14. '#size' => 10,
  15. '#required' => TRUE,
  16. '#ajax' => array(
  17. 'callback' => '_FORM_NAME_generate_output',
  18. 'wrapper' => 'FORM_NAME_output',
  19. 'method' => 'replace',
  20. ),
  21. );
  22.  
  23. // If $form_state['values'] is set, we can set output our value now.
  24. // Otherwise, output a placeholder where the value will be displayed by the
  25. // AJAX callback.
  26. $form['output'] = isset($form_state['values']) ?
  27. _FORM_NAME_generate_output($form, $form_state) :
  28. array('#markup' => '<div id="FORM_NAME_output"></div>');
  29.  
  30. // Add a submit button to our form
  31. $form['submit_button'] = array(
  32. '#type' => 'submit',
  33. '#value' => t('Submit'),
  34. );
  35.  
  36. // Add a submit handler for our form
  37. $form['#submit'][] = '_FORM_NAME_submit';
  38.  
  39. // Return the renderable array for the form
  40. return $form;
  41. }
  42.  
  43. /**
  44.  * Submit callback for our form.
  45.  */
  46. function _FORM_NAME_submit($form, &$form_state) {
  47. // Tell Drupal to rebuild the form after submission. The form function will
  48. // take the values and display them in $form['output'].
  49. $form_state['rebuild'] = TRUE;
  50. }
  51.  
  52. /**
  53.  * Helper function to generate a renderable array of output from the values
  54.  * in the form. It is used both as the AJAX callback and to generate form
  55.  * output when $form_state['values'] is set.
  56.  */
  57. function _FORM_NAME_generate_output($form, $form_state) {
  58. return array(
  59. '#markup' => '<div id="FORM_NAME_output">' . (intval($form_state['values']['x']) * 2) . '</div>',
  60. );
  61. }