Upgrading to Form API

Last modified: May 26, 2008 - 02:44

NOTE: Further details about how the Form API works can also be found in the API reference on the following pages:

Also see the Form Updater module, which can help you get a head start in converting your modules.

Before embarking on the journey to update a module to the new Form API, it is helpful to understand more about the conversion process in general, and the benefits it provides. First, it should be noted that for many module maintainers, converting their module to use the new forms API will be the most difficult and time-consuming conversion yet. "Why is this so much harder to implement than the old approach?" This thought will probably come up more than once if the module being converted has any degree of complexity regarding forms. And the answer to the question is twofold:

  1. The new API is more complex.
  2. The approach is fundamentally different.

It's much easier to get a handle on reason #1 if reason #2 is understood and accepted. :)

The change requires more than simply shifting some code around--it requires re-learning how forms are implemented in Drupal. Unlike the pre-4.7 approach, the creation and handling of form elements is now completely separate from the theming of those elements. This brings both a greater degree of complexity, and a greater degree of flexibility and power to Drupal forms.

Taking the time to learn and implement the API has the following major advantages:

  1. Security
    • It filters the variables passed through _POST, so that only variables that were on the form will be accepted as input
    • It validates select, checkboxes and radios form elements so that only listed options can be checked. Example: the filter_form now validates itself (huge security benefit)
    • It allows you to add additional validation through the form_validate hook, which means that it's a lot simpler to write validation code, and to reuse said validation code. Example: you only need to write the valid_integer function once, and then you can specify whichever form elements need to conform to that.
  2. Extensibility
    • Forms can be reordered
    • Additional form fields can be added
    • The default way a form is validated/executed can be overridden
    • Additional form element types can be added
    • Behavior of default element types can be overridden
  3. Themability
    • Themers can override the default layout of any form or a part of it in their theme
    • Themers can individually theme a single element, a group of elements, or all elements of the same type. Example: one can write a module which would theme multiple selects with checkboxes.

These advantages are available in any form, including those generated by Drupal core!

In addition, this functionality is a major and necessary step towards CCK.

 
 

Drupal is a registered trademark of Dries Buytaert.