Drupal.behaviors: The Two Step Secret To Unlocking Drupal's Javascript

10.12.2008

The hardest part about using drupal's javascript features is knowing where to begin: they remained an arcane mystery to me until today. After drinking a bit of whiskey, and studying how core was using Drupal.behavior, I learned it couldn't be simpler. If you don't know how to do this, take a moment:

Step 1: Invoke the javascript "hook": Drupal.Behaviors.$hook

<?php
/**
* Implementation of hook_form_alter().
* nothing special here
*/
function ajax_comment_form_alter(&$form, &$form_state, $form_id) {
  switch(
$form_id) {
    case
'comment_form':
     
// add the Drupal.ajaxComment.js file
     
drupal_add_js(drupal_get_path('module', 'ajax_comment').'/Drupal.ajaxComment.js', 'module');
     
/*
             *  THIS IS THE TRICK BELOW SO PAY ATTENTION
             *  NOTE A KEYWORD: "ajaxComment" as in $settings['ajaxComment']
             *  Now scan down until I'm yelling in the comments again....
             */
     
$settings['ajaxComment'] = array(
       
// this is all random data we're passing into the js object -- don't worry about it right now
       
'nid' => $form['nid']['#value'],
       
'cid' => $form['cid']['#value'],
       
'uid' => $form['uid']['#value'],
       
'pid' => $form['pid']['#value'],
      );
     
/* BELOW DRUPAL_ADD_JS WILL CALL A FUNCTION (since it exists):
                          -----> Drupal.behaviors.ajaxComment < ---------
                        
              It got that keyword from the key: $settings['ajaxComment']
              We are now done with PHP and step one. Proceed.
              */
     
drupal_add_js($settings, 'setting');
      break;
  }
}
?>

Step 2: Come to understand its just like jQuery now -- only more convenient, and with better support.

This code only breaks comment form submits , and alerts the contents of the submit in a serialized array (ready for an an $.ajax $_POST). Only left this here as a example of some basic ways to take advantage of the setup. All important info is in the code comments of course.

Drupal.behaviors.ajaxComment = function (context) {
  //Drupal.settings.ajaxComment is the javascript version of the contents of $settings['ajaxComment'] in our implementation of hook_form_alter
  Drupal.ajaxComment = new Drupal.ajaxComment($('#comment-form'), Drupal.settings.ajaxComment);
}

Drupal.ajaxComment = function(form, data) {
  var self = this;
  // these are values that aren't changing: cid, nid, uid, pid
  this.formSettings = data;
  //comment form jquery object
  this.form = form;
  // this function is avaliable because of the *prototype keyword* in Drupal.ajaxComment.prototype.submitComment below
  this.submitComment();

};

Drupal.ajaxComment.prototype.submitComment = function(){
  // take note of "self", there's a reason its there
  var self = this;
 
  // self.form is the $('#comment-form') we fed into the new object in Drupal.behaviors.ajaxComment
  this.form.submit( function() {
 
    // this.form.submit, like any jquery method, changes the scope, and suddenly "this" is the form being submitted.
    // since we were super smart, we don't lose access to the ajaxComment object however -- we access it with "self"
   
    //serialize the js form array into strings that can be accessed via $_POST, or $_GET
    self.commentPost($(this).serialize());
    // Since we had the forsight to declare the "self" variable, we can add this data to the object for later use input needs to be sanitized later
    // return false breaks a form submit
    return false;
  });
}

Drupal.ajaxComment.prototype.commentPost = function(post){

  // javascript is freaky....
  alert(post);
  // in a really awesome way...
}

Comments

Great information...sites

Great information...sites like this are part of the reason Drupal Trends are increasing...I wasn't even aware this was possible!

ROFL @ Ballmer Peak!! Many

ROFL @ Ballmer Peak!!

Many thanks for the tutorial, this is something I still have to get my hands seriously dirty with.

BTW, this would make a great dojo lesson - any takers?

Greetings from Barcelona!

thanks mate, great help!

thanks mate, great help! Drupal.Behaviors has been a bit of a blackhole for us for some time now, the whiskey sure helps..
- the doctor

Great stuff Nick, I've had

Great stuff Nick,

I've had some troubles with javascript myself, and so I decided to try your method: I took a couple of whiskey shots... and fell asleep!

Just beware of the Ballmer

Just beware of the Ballmer Peak.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options