Creation an ajax form in simple in Drupal. This article helps to create a simple ajax form to show the entered text above the form without any page refresh or redirect. Creating Form in Drupal is very easy we can create any number of from with any types of fields also. Here I am creating a form with a text field and a submit button to submit the form and on submission the text value entered will be displayed above the form itself. The below is the full code for the same. Create a new custom module if no custom modules are added before. Added the code below inside the module file and clear the cache and check its working fine.
?php
/**
* Implements hook_menu().
*/
function custom_menu() {
$items = array();
$items['simple-form'] = array(
'title' => 'Simple Form',
'page callback' => 'drupal_get_form',
'page arguments' => array('ajax_example_simplest'),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Simple form whose ajax-enabled 'enter_text' member causes a text change
* in the description of the 'replace_textfield' member.
*/
function ajax_example_simplest($form, &$form_state) {
$form = array();
$form['replace_textfield'] = array(
'#type' => 'item',
'#title' => '',
'#prefix' => '<div id="replace_textfield_div">',
'#suffix' => '</div>',
);
$form['enter_text'] = array(
'#title' => t("Enter the text"),
'#type' => 'textfield'
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#ajax' => array(
'callback' => 'ecom_simple_ajax_form_callback',
'wrapper' => 'replace_textfield_div',
),
);
return $form;
}
/**
* Callback for ajax_example_simplest.
*
* The form item 'replace_textfield' has already been processed and changed
* when the form was submitted and rebuilt during the AJAX call, so now
* we just return the piece of the form that changed.
*/
function custom_simple_ajax_form_callback($form, $form_state) {
// The form has already been submitted and updated. We can return the replaced
// item as it is.
if (!empty($form_state['values']['enter_text'])) {
$form['replace_textfield']['#title'] = t("hello") . " '{$form_state['values']['enter_text']}'";
$form_state['values']['enter_text']['#value'] = NULL;
}
return $form['replace_textfield'];
}