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.

Chapter 8<br />

This approach is the proper way to remove form elements from <strong>Drupal</strong>. You may<br />

find yourself tempted to unset() certain form elements, but since <strong>Drupal</strong> forms are<br />

passed by reference through a series of drupal_alter() hooks, the unset() cannot<br />

be considered reliable. Using unset() also removes valuable context that other<br />

modules may be relying on when processing the $form.<br />

Passing secure data via forms<br />

As a general rule, <strong>Drupal</strong> forms do not use the traditional hidden form element<br />

of HTML. Since hidden form elements are rendered in the browser, curious users<br />

(and malicious ones) can view the elements of a form, checking for tokens and other<br />

security devices.<br />

Since <strong>Drupal</strong> is a PHP application, it can use server-side processes to handle secret<br />

form elements, rather than relying on information passed as hidden fields from<br />

the browser.<br />

To pass such data, a form element may be defined as '#type' => 'value'. Using<br />

this Forms API element prevents the data from being rendered to the browser. As<br />

an additional advantage, it also allows for the passing of complex data—such as an<br />

array—during a form request. This technique is commonly used for form elements<br />

that the user should never see such as the id of an element to be deleted during a<br />

confirmation step. Consider the following code from aggregator.module:<br />

function aggregator_admin_remove_feed($form, $form_state, $feed) {<br />

return confirm_form(<br />

array(<br />

'feed' => array(<br />

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

'#value' => $feed,<br />

),<br />

),<br />

t('Are you sure you want to remove all items from the feed<br />

%feed?', array('%feed' => $feed->title)),<br />

'admin/config/services/aggregator',<br />

t('This action cannot be undone.'),<br />

t('Remove items'),<br />

t('Cancel')<br />

);<br />

}<br />

[ 231 ]

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

Saved successfully!

Ooh no, something went wrong!