New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Start learning with our library of video tutorials taught by experts. Get started

Drupal 7 Custom Module Development
Illustration by

Interacting with hooks


From:

Drupal 7 Custom Module Development

with Jon Peck

Video: Interacting with hooks

Drupal uses a unique approach for providing an application programming interface. A hook is a PHP function that allows a module to hook into Drupal and modify behavior. A Drupal hook functions similar to a callback, in that they act as triggered events. Unlike an actual callback, hooks aren't registered with a listener. Instead, Drupal executes hooks based on their name up on a particular event. Hooks are similar to object oriented architecture in several ways.

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
Drupal 7 Custom Module Development
2h 57m Advanced Oct 16, 2012

Viewers: in countries Watching now:

Extend your Drupal 7 sites with custom modules, which allow you to create everything from admin interfaces to forms. Author Jon Peck describes how modules extend your base Drupal installation, then walks through how to write your own module with a practical example featuring geo-positioned alternative energy centers. The course also describes how to control access to site features, create new content types, build forms, understand data persistence, embrace coding standards, and much more.

Topics include:
  • Creating your first module
  • Interacting with hooks
  • Working with permissions and roles
  • Controlling access
  • Adding a menu item to an admin interface
  • Using the Form API (FAPI) to quickly create a form
  • Creating custom form validation
  • Manually creating a custom content type
  • Validating user input
  • Importing content using feeds
  • Creating a block
  • Understanding best practices and coding standards
Subjects:
Developer Web CMS Blogs Web Design Programming Languages Web Development
Software:
Drupal
Author:
Jon Peck

Interacting with hooks

Drupal uses a unique approach for providing an application programming interface. A hook is a PHP function that allows a module to hook into Drupal and modify behavior. A Drupal hook functions similar to a callback, in that they act as triggered events. Unlike an actual callback, hooks aren't registered with a listener. Instead, Drupal executes hooks based on their name up on a particular event. Hooks are similar to object oriented architecture in several ways.

Hooks are constructed with a strict naming convention with function names prefixed with a module name. Similar to an abstract method, each hook has a defined set of parameters and return type. To use a hook, a developer will implement the hook by writing a function that conforms to the naming convention and accepts the same parameters and returns the same type. There are hundreds of hooks available in Drupal core, allowing developers to manipulate practically every aspect of a page build. Some common examples of hooks include, hook_form, which allows robust user facing forms to be created in a standardized manner using the form API; hook_help, which allows a module to make documentation available to the user, and hook_menu, which gives modules the ability to both add items to the site menus and to route page requests to code based on a URL.

A comprehensive list of hooks found in Drupal core can be found at api.drupal.org. In practice, adding a hook to a module is straightforward. One of the first things I look for in a contributed module is the documentation, which also includes built in help. Additionally, having a centralized repository of instructions that can be easily added to as development progresses is a good habit to be in. Therefore, the first hook that I will implement in the windfarms module is hook_help.

For an example of implementation of hook_ help, open your browser and click on Help. You will see a list of Help topics on a number of items, each of which is named after the core module that implements hook_help. I'm going to add a Help for the Wind Farms module to this area. Click on Help, this will describe the purpose of the help module. Notice the path, admin help; this is the base path, then help again; this is the name of the module that is implementing hook_help.

Open your IDE and navigate to the windfarms.module. Before I do anything, I will add documentation in conformance to the Drupal coding standard. It's also just common sense to document your work. I'll create a new documentation block, similar to the file docblock above where the function will go. When implementing a hook, I have the option to document the individual parameters. However, this isn't required as there should already be comprehensive documentation in the original hook. Therefore, it's usually omitted.

According to the standard, all that is needed is the word implements and the name of the hook that is being implemented, which in this case is hook_help followed by parentheses to indicate that a function is being implemented and a period, as this is the end of a sentence; Implements hook_help. Drupal code comment should be written as complete sentences, complete with proper grammar, capitalization and punctuation and a full stop at the end. If a comment spans multiple sentences, only use one space between sentences.

This along with many other coding standard rules may sound needlessly pedantic. Consider the alternative, especially in the context of working with many different developers. By enforcing both their professional approach to internal documentation and coding, one can anticipate the structure, look, and feel of the code base, which leads to easier to understand and adaptable code. Now that the documentation is in place, it's time to add some functionality. To implement a hook, I need to create a function in my module, replacing the word hook with the name of my module and containing the same number of parameters, start with function.

Naming conventions of Drupal hooks dictate that any hook must start with the name of the module, followed by an underscore. As I'm implementing hook_help, I will call this function windfarms_help. According to the Drupal hook_help API, there are two parameters: path and arg. The path parameter contains the router path as defined in hook_menu, which I will get into more detail in a bit. In short, it's similar to a partial URL without the domain or the first slash.

The argument parameter can be safely ignored for now. There is no need for it at the time being. With that said as the parameter exists in the Drupal hook, it must be implemented. Based on the hook_help API, I know that the base limitation is expecting that I switch on the parameter path; switch path. Add a case to the switch for the wind farms module starting with admin/help. The Drupal core help module has made it easy to add a path for each module's documentation.

All that is needed is a pound sign followed by the name of the module that you would like to add documentation for, which in this case is windfarms. According to the API documentation, hook_help returns a localized string containing the help text. Localization is a much larger topic, but in practice, Drupal already has a facility for handling localization, the t function.

The t function translates a string into a particular language. Additionally, it can handle variable replacements within strings as well, which can be very useful. Finally, it also provides string sanitization. Practically speaking, the t function can just be passed a string and written in line with other markup. Due to the way the localization system works, the t function cannot accept a variable. Start by defining a variable for the Return value. I prefer ret_val, start with a standardized heading.

The h3 tag will work nicely. The t function localizes text but should not be used for tags and other HTML elements. Therefore, I will start the header with an h3 tag as just a string, then call the t function. I will describe what this module is for with an About section. Next, concatenate assign a ret-val variable with a paragraph tag followed by the t function containing a high-level explanation about this module. The Wind Farms module makes it easy to manage a database of wind farms, followed by a closing p tag.

Finally return the ret_ val that has been created. Save the wind farms module then, return to the browser and go back to the Help page. You will see no change in the page, why not? The module has not been enabled yet, so Drupal is not interacting with it. Go to the Modules menu item, then scroll to the other group, the Wind Farms module will be listed. Next to it, check the box for Enabled, then click Save configuration.

Now next to the Wind Farms module under Operations, a new option appears named Help. Click on it and the help text that was defined in hook_help will now be displayed. If you click on the breadcrumb for Help, the Wind Farms module will now be listed in the Help topics. In this chapter, I've explored what modules are and how they relate to Drupal, created a barebones module, giving an introspection into the hook interface for extending Drupal, and finally, implemented a Help page using hook_help.

Coming up, I will explore how to access site features in contents that can be controlled with user roles and permissions.

Find answers to the most frequently asked questions about Drupal 7 Custom Module Development.


Expand all | Collapse all
please wait ...
Q: gmap3_tools is not working the way I expected it to. What version of gmap3_tools should I be using?
A: Use the free exercise file containing the version of gmap3_tools used for recording; the published version of the module on drupal.org has changed since recording and is not backwards compatible.
Q: I attempted to run the Drupal site root from the project files, but the site isn't loading. Why not?
A: The Drupal configuration file in sites/default/settings.php contains database configuration specific to the environment used to record the movie. This may be different than your environment. Edit the file and search for "windfarms" - you may need to change the database host, username, password, db name and port to match your specific environment.
 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Drupal 7 Custom Module Development.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.