18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Building an Admin Interface<br />

Form submission process<br />

When an HTML form built with Form API is submitted, <strong>Drupal</strong> looks for two<br />

specifically named functions—a validate function and a submit function. These<br />

functions are named by taking the form ID and appending either _validate()<br />

or _submit() depending on which function you are writing.<br />

The validate function does additional validation beyond what <strong>Drupal</strong> provides. For<br />

instance if you wanted to check to see if a zip code is valid. Even if validation fails<br />

on one element, all validation functions are still called, so <strong>Drupal</strong> can return multiple<br />

errors in a single form. However, if any validation function fails, execution never<br />

proceeds to the submit function.<br />

Validate functions are optional. If you don't need any additional<br />

validation, then you don't have to write one. In this case, <strong>Drupal</strong><br />

will just do its default validation. For more information on how to<br />

write validate functions, see the Form API documentation at the links<br />

referenced earlier in the chapter.<br />

Once the form passes validation, the submit function is called. This is where the real<br />

work is done—saving settings, sending e-mail, and creating content among other<br />

things. The form submit function is one of the main workhorses of <strong>Drupal</strong> modules.<br />

As a module writer you will spend an inordinate amount of time writing submit<br />

functions and support code for submit functions. This is good, because it means you<br />

are spending time on the code that is unique to your project, and not recreating the<br />

wheel every time you want to turn a field red because a required field is missing.<br />

So let's apply this to the User Warn configuration form. The form ID for our<br />

configuration form is user_warn_form, so our submit function will be named<br />

user_warn_form_submit().<br />

Form submit functions take two arguments. $form is the original Form API array<br />

for the submitted form, and $form_state is an associative array containing<br />

information specific to this submission. In particular, $form_state['values']<br />

contains all the submitted form values keyed on their name properties. In general,<br />

$form_state['values'] is the only thing you will need to worry about in validate<br />

and submit functions.<br />

/**<br />

* Save configuration settings for User Warn module.<br />

*/<br />

function user_warn_form_submit($form, &$form_state) {<br />

[ 136 ]

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

Saved successfully!

Ooh no, something went wrong!