NdVO.blog.br

Drupal Hooks

Once you start developing Drupal modules you'll need to learn to use Drupal hooks.

The concept is quite simple. Let's first imagine how Drupal works. It receives a request from a user and returns a Web Page, that is, an HTML formated text. In fact Drupal has to create such HTML text for it is not written anywhere. Drupal will need to understand the request, check if the user requesting has the appropriate permissions, search in a Database for the requested content, retrieve such content and finally build an HTML page with such content.

It will happen very often that you want to add a new rule to a specific step. Drupal was built to make it easy for you to change its behaviour on each step. Thus, when Drupal is about to start to take a step, it first ask if there is any module that wants to do something. The same thing is true when it finishes a step. These calls to each module, asking if they have something to add are hooks.

What actually happens is that Drupal search each module to check if they have a function name with a specific pattern: modulename_hookname. If any module does have such a function, it is executed.

Let's study some examples. When Drupal is about to save a node it runs the hook_node_presave. This means that it will check every installed module for a modulename_node_presave function. If you have a module called custom and a custom_node_presave function, it will run every time Drupal is about to save a node.

This is pretty interesting because you can write your rules without having to change any Drupal code. Simply find the appropriate hook and write your own code in your own module.

Drupal.org has a page that lists all hooks. Check it out. There are some incredibly useful hooks you'll certainly will use from now on. Here are of the hooks I use frequently:

Once you are used to hooks it is unlikely build any Drupal site without using it.

comments powered by Disqus