Drupal display form results below form

Sometimes it is useful to be able to submit a custom form and have the results show below the form. By creating a markup field in the form and by using $form_state['storage'] in a submission handler, here's how I did it:

<?php
 
/**
 * Implements hook_menu();
 */
function mymodule_menu() {
  $items = array();
 
  $items['admin/config/mymodule/mypage'] = array(
    'title' => 'My Page',
    'page callback' => '_mymodule_mypage_content',
    'access arguments' => array('administer users'),
    'type' => MENU_NORMAL_ITEM, // will show up in the navigation (admin) menu
  );
  return $items;
}
 
/**
 * Page callback for admin/config/mymodule/mypage
 */
function _mymodule_mypage_content() {
  return drupal_render(drupal_get_form('mymodule_mypage_form'));
}
 
/**
 * Super rad form.
 */
function mymodule_mypage_form($form, &$form_state) {
  $form['myfield'] = array(
    '#type' => 'textfield',
    '#title' => t('My Field'),
    '#description' => t("Enter some text."),
    '#size' => 20,
    '#maxlength' => 20,
  );
 
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
  );
 
  if (isset($form_state['storage']['results']['myfield'])) {
    $form['results'] = array(
      '#type' => 'markup',
      '#markup' => '<div>' . t('You entered: !date', array('!date' => $form_state['storage']['results']['myfield'])) . '</div>',
    );
  } else {
    $form['results'] = array(
      '#type' => 'markup',
      '#markup' => '<div>' . t('Here is some default text.') . '</div>',
    );
  }
  return $form;
}
 
/**
 * Super rad form submit handler
 */
function mymodule_mypage_form_submit($form, &$form_state) {
  $form_state['storage']['results']['myfield'] = $form_state['values']['myfield'];
  $form_state['rebuild'] = TRUE;
}
 
?>

Tags

Article Type

General