How to create a ajax form in drupal 7

Ajax forms are very cool because  it allows your site users to interact with website without the need to refresh whole page. Drupal 7 comes with a powerful ajax api which is very easy to implement.

In this tutorial, we will learn to create a simple ajax form that does nothing but take values from user and then print it on form submit.

First step is to create a form function

/**
  * Form implementation
  */
function custom_ajax_form($form, $form_state) {
    $form = array();

    $form['#prefix'] = '<div id="custom-ajax-form">'; //wrapper that will be replaced in ajax callback
    $form['#suffix'] = '</div>';

    $form['title'] = array(
        '#type' => 'textfield',
        '#title' => t('Title'),
        '#required' => TRUE
    );

    $form['text'] = array(
        '#type' => 'textfield',
        '#title' => t('Some field'),
        '#required' => TRUE
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#ajax' => array(
            'callback' => 'custom_ajax_callback',
            'wrapper' => 'custom-ajax-form'
        )
    );

    return $form;
}

After this lets implement ajax callback function


function custom_ajax_callback($form, $form_state) {
    return $form; // returning form will refresh the complete form
}

and now lets look into form validation and submit functions

/**
  * Form validation
  */
function custom_ajax_form_validate($form, $form_state) {
    //do the validations here    
}

/**
  * Form submit
  */
function custom_ajax_form_submit($form, &$form_state) {
    drupal_set_message('<pre>' . print_r($form_state['values'], 1) . '</pre>');

    //insert into database or you whatever is required

    $form_state['input'] = array(); //remove user inputted values from form fields
    $form_state['rebuild'] = TRUE; //rebuild form
}

Add new comment