18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5<br />

In past versions of <strong>Drupal</strong>, Form API was commonly referred to as<br />

FAPI. However, <strong>Drupal</strong> 7 now has three APIs which could fit this<br />

acronym—Form API, Field API (which you'll see in Chapter 6 and<br />

Chapter 7) and File API (which you'll learn about in Chapter 11). We<br />

will avoid using the acronym FAPI completely, to prevent confusion,<br />

but you will still encounter it widely in online references.<br />

Form API is also a crucial element in <strong>Drupal</strong>'s security. It provides unique form<br />

tokens that are verified on form submission, preventing Cross-site Request Forgery<br />

attacks, and automatically validating required fields, field lengths, and a variety of<br />

other form element properties.<br />

While Form API is one of the most useful and powerful tools in the module<br />

developer's toolbox, it can also be one of the most complicated. More detailed<br />

information beyond this simple example can be found at the following URLs:<br />

• Form API Quickstart guide:<br />

http://api.drupal.org/api/drupal/developer--topics--forms_api.<br />

html/7<br />

• Form API Full Reference:<br />

http://api.drupal.org/api/drupal/developer--topics--forms_api_<br />

reference.html/7<br />

Using drupal_get_form()<br />

In our first menu implementation seen earlier, we defined the page callback as<br />

drupal_get_form(). This Form API function returns a structured array that<br />

represents an HTML form. This gets rendered by <strong>Drupal</strong> and presented as an HTML<br />

form for the user. drupal_get_form() takes a form ID as a parameter. This form ID<br />

can be whatever you want, but it must be unique within <strong>Drupal</strong>. Typically it will be<br />

__form.<br />

The form ID is also the name of the callback function drupal_get_form() will call<br />

to build your form. The specified function should return a properly formatted array<br />

containing all the elements your form needs.<br />

Since the form ID also serves as the form's callback function, it must be<br />

a valid PHP variable name. Spaces and hyphens are not allowed. All<br />

form IDs should be prefaced by the name of your module followed by<br />

an underscore, in order to prevent name collision.<br />

[ 127 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!