I was working on a patch for poll module today when I made a wonderful discovery.The AHAH (similar to AJAX) enhancements for Drupal core work with all DOM elements, not just form elements (like buttons and select lists). All the code necessary is already in Drupal core, though the following implementation with poll module is still in progress.

The thing I love about Drupal's new AHAH implementation is making javascript available to PHP developers. Here's the extent of code necessary to add this behavior to poll module:

  
  $form['choice_wrapper']['poll_more'] = array(
    '#type' => 'submit',
    '#value' => t('Add another choice'),
    '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),
    '#weight' => 1,
    '#submit' => array('poll_more_choices_submit'), // If no javascript action.
    '#ahah' => array(
      'path' => 'poll/js',
      'wrapper' => 'poll-choices',
      'method' => 'append',
      'effect' => 'slide',
    ),
  );
  

This is the normal FormAPI implementation of ahah.js. All necessary javascript is included on the page as necessary, not a line of javascript needed by the PHP developer.

If we wanted to do the same thing with a link (or DIV, TABLE, or whatever HTML tag you wanted), we could add the javascript to the page manually:

  
$ahah_binding = array(
  'url'   => url('poll/js'),
  'event' => 'click',
  'wrapper' => 'poll-choices',
  'selector' => '#edit-poll-more',
  'effect'   => 'slide',
  'method'   => 'append',
  'progress' => array('type' => 'throbber');
);

drupal_add_js('misc/jquery.form.js');
drupal_add_js('misc/ahah.js');
drupal_add_js(array('ahah' => array($element['#id'] => $ahah_binding)), 'setting');

return 'Click here for more choices';
  

This is a totally untested example, but it shows the necessary code to add AHAH to any element on the page, not just form items. It's pretty cool, and I hope that AHAH will aid in the battle for better usability in Drupal.

Published in

Nate Lampton

Nate Lampton standing in front of greenery.
Nate Lampton is a leader in Open Source with over a decade of contributions to the Drupal project. He joined Lullabot in 2006.