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

Running access checks on forms<br />

While it is perfectly fine to run access checks when building a form, developers<br />

should normally not run access checks when processing a form's _validate() or<br />

_submit() callbacks. Doing so interferes with the logic of hook_form_alter().<br />

For instance, if your module wishes to alter the menu form element above, so that<br />

additional users may add content items to the menu without being able to edit the<br />

entire menu, you can do so easily:<br />

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

if (!empty($form['#node_edit_form']) && isset($form['menu'])) {<br />

$form['menu']['#access'] = example_user_access(<br />

'assign content to menu');<br />

}<br />

}<br />

This code changes the access callback on the menu form element to our own function.<br />

Since hook_form_alter() runs after a form is initially built, we can alter any form<br />

element in this manner.<br />

However, form _validate() and _submit() callbacks are not run through any alter<br />

functions. This means that any access checks that run during those callbacks will<br />

always be imposed. Take for instance, the following example from <strong>Drupal</strong>'s core<br />

node.module, that makes it impossible for normal users to change the author of a<br />

node or the time it was submitted:<br />

/**<br />

* Perform validation checks on the given node.<br />

*/<br />

function node_validate($node, $form = array()) {<br />

$type = node_type_get_type($node);<br />

if (isset($node->nid) && (node_last_changed($node->nid) ><br />

$node->changed)) {<br />

form_set_error('changed', t('The content on this page has<br />

either been modified by another user, or you have already submitted<br />

modifications using this form. As a result, your changes cannot be<br />

saved.'));<br />

}<br />

if (user_access('administer nodes')) {<br />

// Validate the "authored by" field.<br />

if (!empty($node->name) && !($account = user_load_by_name(<br />

$node->name))) {<br />

// The use of empty() is mandatory in the context of usernames<br />

[ 233 ]

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

Saved successfully!

Ooh no, something went wrong!