Difference between revisions of "Hooks system"

From Dolibarr ERP CRM Wiki
Jump to navigation Jump to search
(Better wording)
Tag: 2017 source edit
 
(35 intermediate revisions by 7 users not shown)
Line 1: Line 1:
 +
<!-- BEGIN origin interlang links -->
 +
<!-- You can edit this section but do NOT remove these comments
 +
    Links below will be automatically replicated on translated pages by PolyglotBot -->
 +
[[fr:Système_de_Hooks]]
 +
[[es:El_sistema_Hooks]]
 +
[[de:System_von_Hooks]]
 +
[[en:Hooks_system]]
 +
[[zh:钩子系统]]
 +
<!-- END interlang links -->
 +
[[Category:Hooks]]
 +
 
{{TemplateDocDevEn}}
 
{{TemplateDocDevEn}}
  
= Introduction =
+
=Introduction=
Hooks are a developer feature available since Dolibarr 3.2.
+
Every business always requires something "extra" or different to the Dolibarr core functionality.
It allows developers to add custom code to Dolibarr core without the need to resort to patching.
+
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.
On the contrary of the [[triggers]] (another feature to interact with Dolibarr core code) − which are by definition linked to a business action − hooks can happen anywhere at anytime, they are entry points into the program.
+
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.
* Hooks are enabled or not for a "context" (ie the module, eg: "productcard" for products, "invoicecard" for invoices, etc..). It's easy to find them, just search (or grep) for "'''initHooks('''" into php files.
+
This greatly simplifies the upgrading process by keeping modifications separate from the core code.
* Hooks are parts of code that can be completed or replaced by your own code. You can find all hookable part of code by searching (or grepping) for "'''executeHooks('''".
+
 
 +
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.
  
= Add a hook to allow to insert code =
+
=Adding a hook point into code=
To implement a hook in your own module (so that your module can be ''hooked'' by others), you have two steps to follow.
+
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.
  
These steps must be followed for every php script of your module where you want to implement hooks.
 
  
 +
1- Initialize the HookManager object
  
1- Initialize the HookManager object (put this in the beginning of your script, just after includes):
+
For a page, put this in the beginning of the page (after the include of the main):
  
<source lang="php">
+
<syntaxHighlight lang="php">
 
// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
 
// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
 
include_once(DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php');
 
include_once(DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php');
 
$hookmanager=new HookManager($db);
 
$hookmanager=new HookManager($db);
 
$hookmanager->initHooks(array('context'));
 
$hookmanager->initHooks(array('context'));
</source>
+
</syntaxHighlight>
  
$hookmanager->initHooks() takes 1 parameter (an array of contexts) and activate the hooks management for this script:
+
$hookmanager->initHooks() takes 1 parameter (an array of contexts) and activates the hooks management for this script. '<nowiki/>'''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.
  
- ''''context'''' is a context string. This is simply a indicator that hooking functions can use to detect in which context they are called.
+
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).
  
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 deidcated to your page).
+
For a method or function, you can getthe hook manager with
 +
 
 +
<syntaxHighlight lang="php">
 +
global $hookmanager;
 +
</syntaxHighlight>
  
  
 
2- Place hooks where you want to allow external code:
 
2- Place hooks where you want to allow external code:
  
<source lang="php">
+
<syntaxHighlight lang="php">
 
$parameters=array();
 
$parameters=array();
 
$reshook=$hookmanager->executeHooks('hookname',$parameters,$object,$action); // See description below
 
$reshook=$hookmanager->executeHooks('hookname',$parameters,$object,$action); // See description below
Line 40: Line 70:
 
   ... // standard code that can be disabled/replaced by hook if return code > 0.
 
   ... // standard code that can be disabled/replaced by hook if return code > 0.
 
}
 
}
</source>
+
</syntaxHighlight>
  
 
'''$hookmanager->executeHooks()''' takes 4 parameters and add a hook (an entry point in your script for external functions):
 
'''$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'
+
- '<nowiki/>'''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 more custom data to the hook (the hooking function can then process it). Place here anything you want, it can be a file, an array of strings, anything...
+
- '''$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...
  
 
eg:
 
eg:
<source lang="php">
+
<syntaxHighlight lang="php">
 
$parameters=array('file'=>'my/path/to/a/file', 'customnames'=>array('henry','david','john'));
 
$parameters=array('file'=>'my/path/to/a/file', 'customnames'=>array('henry','david','john'));
</source>
+
</syntaxHighlight>
  
- '''$object''' is the object you want to pass onto the hooking function, mainly the current module's data (eg: 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.
+
- '''$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').
 
- '''$action''' is a string indicating the current action (can be set to null or to something sensible like 'create' or 'edit').
Line 61: Line 91:
 
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.
 
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 =
+
=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.
  
To use a hook (add or replace a part of code), you first need to already have defined a module descriptor (see [[Module_development#Create_your_module_descriptor]]), and then you need to do 2 things:
+
One the descriptor is created, two further steps are required:
  
1- add your module to the list of contexts you want to hook on.
+
1- add your context key to the list of contexts you want to hook on.
This means that when a context you hook will happen, your module hook code will be called.
+
This means that when the core program code is executed into a context, your module hook function will be called.
To do that, just edit your '''/htdocs/''yourmodulename''/core/modules/mod''YourModuleName''.class.php''' and edit the '''$this->module_parts''' variable with something like this:
+
Edit your '''/htdocs/''yourmodulename''/core/modules/mod''YourModuleName''.class.php''' and add the context name to the variable '''$this->module_parts'''.
<source lang="php">
+
eg:
 +
<syntaxHighlight lang="php">
 
$this->module_parts = array(
 
$this->module_parts = array(
 
'hooks' => array('hookcontext1','hookcontext2')  // Set here all hooks context you want to support
 
'hooks' => array('hookcontext1','hookcontext2')  // Set here all hooks context you want to support
 
);
 
);
</source>
+
</syntaxHighlight>
  
Of course change YourModuleName with your own module's name.
+
Don't forget to change YourModuleName to your own module's name!
  
Note: you can find the current module's context with print('Module context: '.$object->context); (put this inside the module's php file where the hook resides and that you want to hook).
+
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:
 +
<syntaxHighlight lang="php">
 +
print('Module context: '.join(',', $object->contextarray));
 +
</syntaxHighlight>
  
[[File:warning.png]] Be careful: do not forget to DISABLE then ENABLE the module in the admin panel to accept the new context, because these constants are only added to the database when enabling the module.
+
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).
  
 +
[[File: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 overload a hook (a function) with your own.
+
 
 +
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:
 
Create a file '''/htdocs/''yourmodulename''/class/actions_''yourmodulename''.class.php''' and then put something like this:
  
<source lang="php">
+
<syntaxHighlight lang="php">
 
class ActionsYourModuleName
 
class ActionsYourModuleName
 
{  
 
{  
+
/**
    /** Overloading the doActions function : replacing the parent's function with the one below  
+
* Overriding the doActions function : replacing the parent function with the one below
    * @param     parameters meta datas of the hook (context, etc...)  
+
*
    * @param     object             the object you want to process (an invoice if you are in invoice module, a propale in propale's module, etc...)  
+
* @param   array()        $parameters     Hook metadatas (context, etc...)
    * @param     action             current action (if set). Generally create or edit or null  
+
* @param   CommonObject    &$object       The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
    * @return       void
+
* @param   string          &$action       Current action (if set). Generally create or edit or null
    */  
+
* @param  HookManager    $hookmanager    Hook manager propagated to allow calling another hook
    function doActions($parameters, &$object, &$action, $hookmanager)  
+
* @return int                            < 0 on error, 0 on success, 1 to replace standard code
    {  
+
*/
        print_r($parameters);  
+
function doActions($parameters, &$object, &$action, $hookmanager)
        echo "action: ".$action;  
+
{
        print_r($object);  
+
$error = 0; // Error counter
+
$myvalue = 'test'; // A result value
        if (in_array('somecontext',explode(':',$parameters['context'])))  
+
 
        {  
+
print_r($parameters);
          // do something only for the context 'somecontext'
+
echo "action: " . $action;
        }
+
print_r($object);
 +
 
 +
if (in_array('somecontext', explode(':', $parameters['context'])))
 +
{
 +
  // do something only for the context 'somecontext'
 +
}
  
        if (! $error)
+
if (! $error)
        {
+
{
            $this->results=array('myreturn'=>$myvalue)
+
$this->results = array('myreturn' => $myvalue);
            $this->resprints='A text to show';
+
$this->resprints = 'A text to show';
            return 0; // or return 1 to replace standard code
+
return 0; // or return 1 to replace standard code
        }
+
}
        else
+
else
        {
+
{
            $this->errors[]='Error message';
+
$this->errors[] = 'Error message';
            return -1;
+
return -1;
        }
+
}
    }
+
}
 
}  
 
}  
</source>
+
</syntaxHighlight>
  
Your function should now be called when you access the module/context and you will see the parameters and object and action.
+
Your function should now be called when the program executes the module/context and you will see the parameters and object and action.
  
 
'''Where''':
 
'''Where''':
* '''$parameters''' is an array of meta-data about the datas contained by the hook (eg: the context, always accessible by $parameters['context']).
+
 
* '''$object''' is the object that you may work on. Eg: the product if you are in the productcard context.
+
*'''$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.
* '''$action''' is the action if one is conveyed (generally "create", "edit" or "view").
+
*'''$object''' is the object/data that you may work on. Eg: the product if you are in the productcard context.
* '''$hookmanager''' is propagated only to allow your hook to call another hook.
+
*'''$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.
  
 
'''Returns''':
 
'''Returns''':
* The return code from a hook is 0 or 1 if success, negative if error. In general, it will be 0. It can be 1, which means that, in some specific cases, your code hook completely replaces what Dolibarr would do without the hook. If return code is negative, 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 enriched with the contents of this array, which can be reused later.
 
* If the method sets the property $this-> resprints with a string, then this string will be displayed by the manager hook (executeHook), immediately after your method exit.
 
* Your code can also modify the value of $object and $action.
 
  
= List of available Hooks in Dolibarr =
+
*The return code from a hook ($reshook) is 0 / 1 if successful, or negative if in error.
How to find a complete list of all available hooks in Dolibarr's nomenclatura ?  
+
 
 +
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.
 
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]]
  
This is however a small list of them (not complete):
+
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.
{{ListOfHooks}}
 
...
 
  
Note: please note that this list may change in the future 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.
  
= List of available Contexts in Dolibarr =
+
This is a small list of them (not complete):
To find the complete list of available modules' context in Dolibarr's nomenclatura, 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 however a small list of them (not complete):
 
 
{{ListOfContexts}}
 
{{ListOfContexts}}
 
...
 
...
  
Note: please note that this list may change in the future as hooks and contexts are added into Dolibarr, so if you really need to find a specific hooks, please search directly in the sourcecode.
+
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=
 +
 
 +
*[[Triggers]]
 +
*[[Interfaces Dolibarr toward foreign systems]]
 +
*[[Interfaces from foreign systems toward Dolibarr]]
  
= See also =
+
[[Category:Development]]
* [[Triggers]]
 
* [[Interfaces Dolibarr toward foreign systems]]
 
* [[Interfaces from foreign systems toward Dolibarr]]
 

Latest revision as of 00:37, 26 January 2024


Introduction

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
include_once(DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php');
$hookmanager=new HookManager($db);
$hookmanager->initHooks(array('context'));

$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:

$parameters=array();
$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...

eg:

$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

		print_r($parameters);
		echo "action: " . $action;
		print_r($object);

		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
		}
		else
		{
			$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.

Where:

  • $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.

Returns:

  • 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