Hooks system

From Dolibarr ERP CRM Wiki
Jump to navigation Jump to search


Every business always requires something "extra" or different to the Dolibarr core functionality. While all improvements and extensions to the Dolibarr code should be contributed back via Github to be included in a future version, some modifications will be too specific to be of interest to all. Hence the Hooks system was introduced in Dolibarr. This allows developers to add custom code/features to the Dolibarr core files without the need to modify the core files. This greatly simplifies the upgrading process by keeping modifications separate from the core code.

As opposed to triggers (actions linked to a business event) − hooks are entry points into the program and can modify any part of the program functions. There are many hooks already built into the code and you may add more. They can be considered a point where the code execution is diverted "out" of the current page and runs your code, then returns back. Your custom code may add something or modify an object or completely replace an existing code block, depending on the implementation of the hook in that specific instance.

Every hook has a name, eg. "doActions" found in this code: $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); However the hook name is often not unique (may be repeated in various code modules), so to identify the location accurately, code modules have a "context" name that will be referred to by all hooks in that code module location. So to use a hook, you need to know its context name (its location) and the hook name.

  • The Hook Context Name (e.g.: "productcard" for products, "invoicecard" for invoices, etc..). can be found by searching for "initHooks(" in the php files.

This will find results such as "$hookmanager->initHooks(array('thirdpartycomm','globalcard'));" where "thirdpartycomm" is the context.

  • The Hook Name can be found by searching for "executeHooks(" in the block of code you are interest in modifying...possibly there may be no hook defined so you may add your own (and submit a corresponding pull-request in Github so it gets included in a future version).

This will find results such as "$reshook = $hookmanager->executeHooks('addMoreBoxStatsCustomer', $parameters, $object, $action);" where "addMoreBoxStatsCustomer" is the Hook name.

Adding a hook point into code

To add a hook into a module (so that the module can be hooked by others), two code additions are required in each php script where you want to implement hooks. Hooks are implemented in Dolibarr core modules in the same manner.

1- Initialize the HookManager object

For a page, put this in the beginning of the page (after the include of the main):

// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
$hookmanager=new HookManager($db);

$hookmanager->initHooks() takes 1 parameter (an array of contexts) and activates the hooks management for this script. 'context' is a context string. This is simply a indicator that hooking functions can use, to detect in which context they are called. Note that the context 'all' is always valid.

Note: you can set several contexts in the same init (for example if you want to have a common context into several pages and want also a specific context dedicated to your page).

For a method or function, you can getthe hook manager with

global $hookmanager;

2- Place hooks where you want to allow external code:

$reshook=$hookmanager->executeHooks('hookname',$parameters,$object,$action); // See description below
// Note that $action and $object may have been modified by hook
if (empty($reshook))
   ... // standard code that can be disabled/replaced by hook if return code > 0.

$hookmanager->executeHooks() takes 4 parameters and add a hook (an entry point in your script for external functions):

- 'hookname' is the hook's name as a string (can be anything you want, or you can follow the Dolibarr's nomenclatura, look at the list of hooks below). eg: 'formObjectOptions'

- $parameters is a custom array to send data to the hook so the hooking function can process it. It can be a file, an array of strings, anything...


$parameters=array('file'=>'my/path/to/a/file', 'customnames'=>array('henry','david','john'));

- $object is the object you want to pass onto the hooking function, usually the current module's data (eg: the invoice object if it is invoice module, etc..). This can be anything you want, but remember this will be the main component hooking functions will be using.

- $action is a string indicating the current action (can be set to null or to something sensible like 'create' or 'edit').

Note: You will want to redo this step if you want to add multiple hooks at different places in your script.

Now your module should be hookable, and you can follow the procedure below in Implement a hook to implement a hooking function that will take advantage of your new hooks.

Implement the Hook functions

To use a hook (to add to/replace a part of code), you first need to already have defined a module descriptor (see Module_development#Create_your_module_descriptor). Using a hook function is a part of creating a custom module, so please use the built-in Module Builder to easily create a custom module from a template so you can then modify the relevant hook section.

One the descriptor is created, two further steps are required:

1- add your context key to the list of contexts you want to hook on. This means that when the core program code is executed into a context, your module hook function will be called. Edit your /htdocs/yourmodulename/core/modules/modYourModuleName.class.php and add the context name to the variable $this->module_parts. eg:

$this->module_parts = array(
'hooks' => array('hookcontext1','hookcontext2')  // Set here all hooks context you want to support

Don't forget to change YourModuleName to your own module's name!

Note: one way to determine the name of contexts you are when you reach a part of code is to add this code in the PHP code:

print('Module context: '.join(',', $object->contextarray));

Note that the all context means you want your hook beeing executed whatever is the context. The main means you want your hook to be executed for any web page, and cli means in every Command Line script (even if you can't see this context keys in $object->contextarray).

Warning.png Note that when you add a new context name to the 'hooks' => array, this list of contexts must be stored in the database. This only occurs when the custom module is enabled. So, when you add/remove/modify/rename any context name, you MUST disable and enable the custom module for the changes to take effect.

2- You will override a hook (a function) with your own function.

Create a file /htdocs/yourmodulename/class/actions_yourmodulename.class.php and then put something like this:

class ActionsYourModuleName
	 * Overriding the doActions function : replacing the parent function with the one below
	 * @param   array()         $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    &$object        The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          &$action        Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	function doActions($parameters, &$object, &$action, $hookmanager)
		$error = 0; // Error counter
		$myvalue = 'test'; // A result value

		echo "action: " . $action;

		if (in_array('somecontext', explode(':', $parameters['context'])))
		  // do something only for the context 'somecontext'

		if (! $error)
			$this->results = array('myreturn' => $myvalue);
			$this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
			$this->errors[] = 'Error message';
			return -1;

Your function should now be called when the program executes the module/context and you will see the parameters and object and action.


  • $parameters is an array of meta-data about the datas contained by the hook. Note the calling context is stored in $parameters['context'] which is added to the array when it branches through hookmanager.
  • $object is the object/data that you may work on. Eg: the product if you are in the productcard context.
  • $action is the action if one is passed (generally "create", "edit" or "view").
  • $hookmanager is propagated only to allow your hook to call another hook.


  • The return code from a hook ($reshook) is 0 / 1 if successful, or negative if in error.

Return Code 0. In this case if the subsequent core module code function is enclosed by if (empty($reshook)) {...} it will execute as normal but with the data modified by your custom function.

Return Code 1. In this case if the subsequent core module code function is enclosed by if (empty($reshook)) {...} it will not execute at all. So this means it has been replaced by your custom function.

Return code is negative if an error has occurred in your function. You can also set $this->errors[]='Error message to report to user'

  • If the method sets the property $this->results with an array, then the array $hookmanager->resArray will automatically be loaded with the contents of this array, may be reused later.
  • If the method sets the property $this->resprints with a string, then this string will be displayed by the hook manager (method executeHook), immediately after your method exit.
  • Your code may also modify the value of $object and $action.

List of available Hooks in Dolibarr

How to find a complete list of all the available hooks in Dolibarr core code? Just search for "executeHooks(" through the whole sourcecode (generally called "find in files") and you should easily find all the hooked methods calls. There are many, and more are added in each version update. This is small list of some example hooks (not up to date/complete): Hooks

Note: please note that this list changes continually as hooks and contexts are added into Dolibarr, so if you really need to find a specific hooks, please search directly in the sourcecode.

List of available Contexts in Dolibarr

To find a complete list of available module context names in Dolibarr, the procedure is similar to finding hooks. Search for "initHooks(" through the whole sourcecode (generally called "find in files") and you should find all the possible contexts.

This is a small list of them (not complete):

adherents\card.php(111): membercard
adherents\type.php(73): membertypecard
categories\categorie.php(96): categorycard
comm\card.php(72): commcard
comm\propal.php(99): propalcard
comm\action\card.php(85): actioncard
comm\action\index.php(112): agenda
comm\mailing\card.php(55): mailingcard
commande\card.php(93): ordercard
compta\facture.php(105): invoicecard
compta\paiement.php(70): paiementcard
compta\deplacement\card.php(50): tripsandexpensescard
compta\dons\card.php(53): doncard
compta\localtax\clients.php(172): externalbalance
compta\salaries\card.php(47): salarycard
compta\tva\card.php(45): taxvatcard
contact\card.php(77): contactcard
contrat\card.php(70): contractcard
expedition\card.php(85): expeditioncard
fichinter\card.php(80): interventioncard
fourn\card.php(54): suppliercard
fourn\commande\card.php(80): ordersuppliercard
fourn\commande\orderstoinvoice.php(88): orderstoinvoicesupplier
fourn\facture\card.php(72): invoicesuppliercard
fourn\facture\paiement.php(71): paymentsupplier
livraison\card.php(68): deliverycard
product\card.php(91): productcard
product\composition\card.php(55): productcompositioncard
product\fournisseurs.php(62): pricesuppliercard
product\stats\commande.php(45): productstatsorder
product\stats\commande_fournisseur.php(45): productstatssupplyorder
product\stats\contrat.php(45): productstatscontract
product\stats\facture.php(48): productstatsinvoice
product\stats\facture_fournisseur.php(47): productstatssupplyinvoice
product\stats\propal.php(45): productstatspropal
product\stock\card.php(54): warehousecard
projet\card.php(48): projectcard
projet\tasks.php(67): projecttaskcard
resource\card.php(60): resource_card
resource\element_resource.php(58): element_resource
societe\agenda.php(41): agendathirdparty
societe\commerciaux.php(40): salesrepresentativescard
societe\consumption.php(80): consumptionthirdparty
societe\info.php(41): infothirdparty
societe\soc.php(80): thirdpartycard
user\card.php(93): usercard
user\list.php(72): userlist
user\passwordforgotten.php(56): passwordforgottenpage

Note: please note that this list changes as hooks and contexts are added into Dolibarr, so if you really need to find a specific context, please search directly in the sourcecode.

See also