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 />

<strong>Drupal</strong> also offers a Form API element of type 'hidden', should<br />

developers prefer to use it.<br />

Form API makes form building incredibly simple, but right now this form has two<br />

problems. First, the module should provide some reasonable default settings for<br />

system administrators. Second, when you submit the form, none of the submitted<br />

data is actually handled in any way. Let's take a brief detour from form handling<br />

and look at how <strong>Drupal</strong> manages persistent system data.<br />

Managing persistent data<br />

<strong>Drupal</strong> provides a mechanism by which data, which needs to persist semipermanently<br />

(like system settings), can be saved and retrieved. These items are<br />

somewhat confusingly referred to as 'variables' (we will refer to them specifically<br />

as persistent variables from here on to avoid confusion). Persistent variables are<br />

stored in a database table, keyed by a unique name provided by the module that<br />

implements them.<br />

Persistent variables are saved using variable_set(), and retrieved using<br />

variable_get(). These variables can be any type of data that a developer needs, be<br />

it a simple string, an associative array, or a PHP object. The <strong>Drupal</strong> API for setting/<br />

getting them takes care of all the serialization/unserialization that is necessary<br />

behind the scenes.<br />

variable_get() can also provide a default value, which is useful for situations<br />

where you need a variable which has not already been set, for instance, after a<br />

module is installed for the first time. We can use this to our advantage in our<br />

configuration form as shown in the following snippet:<br />

$form['user_warn_e-mail_subject'] = array(<br />

'#type' => 'textfield',<br />

'#default_value' => variable_get('user_warn_e-mail_subject',<br />

'Administrative Warning'),<br />

'#title' => t('Warning e-mail subject'),<br />

'#size' => 40,<br />

'#maxlength' => 120,<br />

'#required' => TRUE,<br />

'#description' => t(<br />

'The subject of the e-mail which will be sent to users.'),<br />

);<br />

[ 133 ]

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

Saved successfully!

Ooh no, something went wrong!