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

This is the same Form API element we created above, but with a new line added.<br />

This line adds the '#default_value' property of the form element. This property<br />

tells the form what data the element should contain when the form is first loaded.<br />

We are assigning this property the results of a call to variable_get() using two<br />

parameters. The first parameter is the unique key associated with this data. It is<br />

common practice to give a persistent variable the same name as the form element<br />

it is associated with, and we have done so here.<br />

Like menu items, persistent variables are cached by <strong>Drupal</strong>, so you<br />

will often need to clear your caches after modifying them.<br />

The second parameter specifies the data that should be returned if this variable<br />

has never been explicitly set. In this example we have set that to be the string<br />

'Administrative Warning'. If this variable had been explicitly set sometime<br />

previously, then that data will be returned by variable_get() instead. Otherwise,<br />

the default value will be returned.<br />

Now the first time the form loads, whatever data is in the persistent variable<br />

'user_warn_e-mail_subject' will be set as the value of the e-mail subject form<br />

element. We can also do this to our other form elements as desired. In the end our<br />

function will be as follows. Note that we have also added a constant containing the<br />

default text of our e-mail. Removing this large block of text from our array definition<br />

makes our code more readable and maintainable down the road.<br />

<strong>Drupal</strong> constants are typically defined at the top of a .module file, but for the sake<br />

of clarity this example includes the constant definition with the function:<br />

define('USER_WARN_MAIL_TEXT',<br />

'Hello,<br />

We have been notified that you have posted comments on our site that<br />

are in violation of our terms of service. If this behavior continues<br />

your account will be suspended.<br />

Sincerely,<br />

The administrative staff');<br />

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

$form = array();<br />

// Text field for the e-mail subject.<br />

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

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

[ 134 ]

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

Saved successfully!

Ooh no, something went wrong!