How to replace/update multiple form fields in drupal ajax callback

In the previous tutorial, we learnt how to create a simple ajax form which replaces complete form in ajax callback.

However there are cases where we need to update/replace/refresh individual or multiple form elements in ajax callback. In this tutorial, we'll learn how to replace individual or multiple fields at once using Drupal ajax command framework.

First, each form element that should be updated with ajax command should be wrapped in a div with unique css class or id. We can use "#prefix" and "#suffix" for this.

$form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
    '#prefix' => '<div id="title-wrapper">',
    '#suffix' => '</div>'
);

$form['text'] = array(
    '#type' => 'textfield',
    '#title' => t('Some field'),
    '#required' => TRUE,
    '#prefix' => '<div id="some-field-wrapper">',
    '#suffix' => '</div>'
);

Now, lets implement the ajax callback

function custom_ajax_callback($form, $form_state) {
    if(!form_get_errors()) { //only if form has no errors
        $commands = array();
        $commands[] = ajax_command_replace('#title-wrapper', render($form['title']));
        $commands[] = ajax_command_replace('#some-field-wrapper', render($form['text']));
        return array('#type' => 'ajax', '#commands' => $commands);
    }
    else {
        return $form;
    }
}

 

Add new comment