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.

In the first case, Are we looking at a user page? is a question our module does<br />

not need to ask. We know through the API that using hook_user_view() only<br />

fires when someone is looking at a user's information. So we don't need our own<br />

permission check for that action.<br />

What matters to us is the question Are we a trusted user? Here we may have<br />

to create a permission check.<br />

Chapter 8<br />

We could simply use the existing administer users permission provided by core,<br />

but is that the best solution? In many use cases, it is likely to be. However, suppose<br />

you are building a newspaper website. In this scenario, we have "site editors" whose<br />

job is to supervise the work of others. To do so, these editors need to be able to check<br />

the content types that a user can create. However, administer users is a much more<br />

powerful permission, which allows the editing of user accounts and the assigning of<br />

user roles. We may not want to give that much authority and responsibility to our<br />

site editors.<br />

In this case—in fact, in most cases—the creation of a discrete permission for each<br />

action is the best choice. Since you cannot reliably predict all the usage scenarios for<br />

your code, piling too many actions onto a single permission can limit how people can<br />

use your module. Any time you see yourself writing an administer X permission in<br />

the code, you should ask yourself if that permission can be made more granular.<br />

Writing hook_permission()<br />

For our example module, then, we need to define a permission that grants the ability<br />

to view this information about users. Our permission array is quite direct, and has<br />

three possible parts:<br />

1. The machine-readable name of the permission. This element will be used<br />

by the module code to check user_access(). For our example, we use the<br />

string "view content creation permissions". By convention, this string must<br />

be in English and all lower case. It need not be a complete sentence.<br />

2. The human-readable label for the permission. This may be the same as the<br />

machine-readable string, but should be formatted with an initial capital.<br />

You may capitalize words as needed. Unlike the machine-readable name,<br />

this string must be wrapped in t() so that the output may be translated.<br />

We will use "View the content creation options for registered users" because<br />

anonymous users do not have an account page to view.<br />

[ 219 ]

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

Saved successfully!

Ooh no, something went wrong!