AJAX

Form API Changes for Drupal 7, Part 2: AJAX/AHAH Changes

Continuing from Form API Changes for Drupal 7, Part 1: $form_state changes.

One of the many pleasant improvements to the Drupal Form API is that AJAX Forms are now really easy. Really easy. We used to call them AHAH forms, and the concept was the same, but they were so complicated that few people attempted them. In D7 we even changed the name to distance ourselves from "AHAH" :-)

In Drupal 6 you had to make a menu entry in hook_menu() that pointed to an AJAX callback handler that was complete black magic. (See a sanitized example.) People did this part differently, and it was hard to figure out the right way. (If you're doing D6 AHAH, the gory details and resources are here.)

In Drupal 7 there is none of that. But we still have to start with the basics so that you'll understand what's going on:

In this example, we just use checkboxes to determine whether textboxes are displayed.

One of the fundamental ideas of having a form change based on selections within the form is that the form is reconfiguring itself based on $form_state. So here, the generation of the form is driven by $form_state['values']. If the checkbox for last name is checked, then we generate a textfield for last name.

Topics: 
Topics: 

The essence of AJAX forms is that you mark an element of a form as the one that activates AJAX behavior, and you tell it what section of the HTML is to be replaced when it's activated.

The form we're using here has a textfield with a description, which is just plain HTML. It has a prefix and suffix that mention its CSS ID. The CSS ID will be used by the javascript running in the background to determine what's to be replaced.

Topics: 

It's pretty easy to forget all the details of the Drupal Forms API, so we'll stop for a minute for a very short review.

(This one is at ahah_demo/simple_form.)

You add a form to your page like this:

Topics: 
  • Book module (core) (Rebuilds the form so you can select an appropriate book and parent page)
  • Poll module (core) (Click a submit button and it adds another question)
  • Examples module (Drupal 7) provides a number of AJAX examples in the "AJAX Example module".
  • Quicktabs module (Configuration options change with the type of tab)
Topics: 

Drupal 7 AHAH has changed its name to AJAX to use a more familiar term and to be slightly more trendy. A version of this presentation for D7 AJAX is at http://randyfay.com/ajax. D7 AJAX handling is massively simplified.

The AJAX Example for D7 is now in the Examples Module and will be maintained there. If you find AJAX features that you'd like to see in it that aren't there, file a request or submit a patch.

Subscribe to AJAX
Drupal theme by Kiwi Themes.