Creating a Drupal Module — Part 4: Exposing Functionality and Enforcing Permissions
Drupal's module system is very powerful and flexible, allowing you to do almost anything you can think of. Some of the simple modules will create a content block such as a sidebar menus. Others act as an input filters such as parsing line breaks into HTML's <br /> tags. A module could even be as simple as exposing a library of custom PHP functions tailored to your site.
For this example, we are going to make a publicly exposed PHP function which simply prints out the current date/time. Open up your testmod.module file and create a function which returns the current date and time. It is a good idea to prefix all function names with your module name to avoid name collisions.
function testmod_get_datetime( ) { if ( user_access('access testmod function') ) return date( 'F j, Y, g:i a' ); return ''; }
The first line of the function checks permissions via Drupal's user_access function. If the currently logged in user has access based on permissions set in part 3, the current date and time is shown. Otherwise, the function returns an empty string.
To test, create a new node, switching to an input mode which allows rending of PHP. Call the function as you would any other function.
<!-- Display greeting --> Today is <?php print testmod_get_datetime( ); ?>. Good day to you!
This is works perfectly, but having to switch to a PHP-rending input mode is not ideal. In the next section, we will use the _filter hook to allow for cleaner integration.
- Add new comment
- 983 reads