Thursday, September 29, 2011

AJAX Forms in Drupal 7

<?php/**
* AJAX-enabled select element causes replacement of a set of checkboxes
* based on the selection.
*/
//the AJAX-enabled element is a select, $form['howmany_select'], which causes replacement of the HTML ID 'checkboxes-div' (named in #ajax['wrapper']), which is a wrapper around a the fieldset $form['checkboxes_fieldset']:

function ajax_example_autocheckboxes($form, &$form_state) {

 
$default = !empty($form_state['values']['howmany']) ? $form_state['values']['howmany'] : 1;

 
$form['howmany_select'] = array(
   
'#title' => t('How many checkboxes do you want?'),
   
'#type' => 'select',
   
'#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
   
'#default_value' => $default,
   
'#ajax' => array(
     
'callback' => 'ajax_example_autocheckboxes_callback',
     
'wrapper' => 'checkboxes-div',
     
'method' => 'replace',
     
'effect' => 'fade',
    ),

  );


 
$form['checkboxes_fieldset'] = array(
   
'#title' => t("Generated Checkboxes"),
   
// The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
   
'#prefix' => '<div id="checkboxes-div">',
   
'#suffix' => '</div>',
   
'#type' => 'fieldset',
   
'#description' => t('This is where we get automatically generated checkboxes'),
  );

When the 'howmany_select' element is changed, a background request is issued to the server requesting that the form be rebuilt. After the form is rebuilt, using the changed 'howmany' field as input on how to rebuild it, the callback is called:

  $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;
  for (
$i=1; $i<=$num_checkboxes; $i++) {
   
$form['checkboxes_fieldset']["checkbox$i"] = array(
     
'#type' => 'checkbox',
     
'#title' => "Checkbox $i",
    );
  }

 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('Submit'),
  );

  return
$form;
}
/**
* Callback element needs only select the portion of the form to be updated.
* Since #ajax['callback'] return can be HTML or a renderable array (or an
* array of commands), we can just return a piece of the form.
*/
function ajax_example_autocheckboxes_callback($form, $form_state) {
  return
$form['checkboxes_fieldset'];
}
?>
The callback in this case (and in many cases) just selects the portion of the form which is to be replaced on the HTML page and returns it. That portion of the form is later rendered and returned to the page, where it replaces the #ajax['wrapper'] which was provided.
That's AJAX forms in a nutshell. A form element with the #ajax property submits a background request to the server when it is triggered by a click or change. The form gets rebuilt (on the server) by the form-builder function, and then the callback named in #ajax['callback'] is called, which selects the portion of the form to return for replacement on the original page.

No comments:

Post a Comment