Skip to main content

What is hook and How to add a hook in Drupal 7?

How to add a hook in Drupal 7

This is the general question when you start learning the drupal hooks. So, if you want to know how to create and add a hook in Drupal 7 then this is the ideal article for you:

What is Hook?

A hook is a drupal function that is provided by a module to enhance the existing functionality of another module. For example, the 'node' module provides the core features of a node (content type), like you can modify content before the node is saved using "hook_node_presave".

By creating your own custom hooks, you can empower others to modify or extend the functionality of custom modules without affecting their core functions. It takes flexibility to the next level and simplifies the tasks. Now, you might be curious to know that how hook is created and how does it work?

Here I'm going to explain you step by step process of creating and implementing hooks.

How to add hook in Drupal 7

Suppose you have a content type "Insurance" with fields (Name, DateOfBirth, Age, InsurancePremium)

Step 1: Create a module with .info and .module files

Step 2: Create a custom form with submit handler. When this form is submitted the corresponding data filled in the fields is stored in the database as it is.

Step 3: Now if you want that any other person using this module can calculate the premium according to the age provided without modifying the submit handler then the first thing you have to do is to create a hook using: "module_invoke_all("modify_premium" , $data)" in the submit handler. here $data represents the data you want to make available to the other module.

I chose "Submit Handler" because I wanted to modify the content before the content is saved.

You can use the hook in other module by writing "hook_modify_premium". Here, "hook" is the name of module implementing it. Now you can write the code in this hook then code written in the "hook_modify_premium" will be executed at the place where we defined the hook using "module_invoke_all("modify_premium",$data)".

Important to Remember: module_invoke_all() never entertains the variables passed by reference, so if you want to alter any content then you either use drupal alter or pass an object with module_invoke_all().

Want to develop a project in Drupal? Contact us.

Read More: 10 best modules to further extend the functionality of Drupal 8

Submitted by cmsadmin on Wed, 05/17/2017 - 04:20


Worldwide Clients



Successful Projects



Team Members



Years in Industry


Awards And Accreditation