• Avail guidance to develop Drupal modules & Drupal themes
  • Share and get review of your code
  • Get Access to free CodeBooks and ThemeBooks
  • Drupal 5, 6 and 7 covered

Userpoints Meter

0 Points /1000 Points

Drupal hook: hook_init

Drupal executes code with hooking into modules and evaluates the code within the hook.
One of such hooks is hook_init(). It gets executed on every page loads. This hook is useful when, we need some functionality, code or script get executed on every page loads. For example, instead of altering the page.tpl.php, we can include any js or css files on a page by loading them in hook_init. This way, the module can be used widely and need not to change any files.

Developers who develop custom modules, can use this hook for loading css or js file for every page, and thus making the module truly plugable in Drupal.

When creating a custom module, there are few things that should be considered. Like, the module should have as much as low dependencies. This makes your module more easily installable. Module should include and load files required for a feature offered by the module, withing module and all those files should reside in the module directory, i.e. inc file, javascript and style sheet for module specific theming. If you are tweaking some of the core styling, the files should be included on each page loads. Instead of suggesting to modify the tpl files, this can be achieved by writing codes for loading those files in hook_init().

i.e.

<?php
function mymodule_init() {
 
//Following js will be loaded on each page loads. Thus avoiding to modify the page.tpl.php
 
drupal_add_js(drupal_get_path('module', 'mymodule')  ."/highligh.js");
}
?>

5
Your rating: None Average: 5 (2 votes)
Syndicate content

Recent comments