Login

Drupal7 Form API Ajax Directives

Drupal 7 adds "ajax" attributes to the Form API (FAPI).

In our example below, we've added ajax attributes to our "report" button. When a user "clicks" on the button, we will send a request to a server side handler named "my_color_ajax_response". When the server side handler sends a response, we replace the contents of the html div element "report_table". We use the tag "id" attribute to identify the appropriate target html div tag.

function color_form($form,&$form_state) {
 
    $weight = 0;
 
    $form['fs'] = array(
      '#type'=>'fieldset',
      '#attributes'=>array('style'=>'width:50%;'),
      '#weight'=>$weight,
    );
 
    $form['fs']['color']=array(
        '#type'=>'textfield',
        '#required'=>true,
        '#default_value'=>'',
        '#title'=>t('Enter Red, White or Blue'),
        '#size'=>25,
        '#maxlength'=>60,
        '#weight'=>$weight);
 
    $form['fs']['report']=array(
        '#type'=>'button',
        '#attributes'=>array('style'=>'float:right;margin-left:2px;margin-top:20px;'),
 
        '#ajax' => array(
                'event'=>'click',
                'callback' => 'my_color_ajax_response',
                'wrapper' => 'report_table',
        ),
        '#value'=>'Vote',
        '#weight'=>$weight++);
 
    $form['message-area'] = array(
        '#type'=>'markup',
        '#markup'=>'<div id="inner-message" class="info">&nbsp;</div>',
        '#prefix'=>'<div id="message_area">',
        '#suffix'=>'</div>',
        '#weight'=>$weight++,
    );
 
    $form['report-table'] = array(
        '#type'=>'markup',
        '#markup'=>theme_table(_get_color_vote()),
        '#prefix'=>'<div id="report_table">',
        '#suffix'=>'</div>',
        '#weight'=>$weight,
    );
 
    return $form;
}