El sistema Hooks: Difference between revisions

Jump to navigation Jump to search
no edit summary
(Created page with "{{TemplateDocDevEs}} {{ToTranslate}} Hooks is a developer feature to allow developer to add personalized code intod Dolibarr core code with no need to patch Dolibarr. On the con...")
 
No edit summary
Line 1: Line 1:
{{TemplateDocDevEs}}
{{TemplateDocDevEs}}
{{ToTranslate}}


Hooks is a developer feature to allow developer to add personalized code intod Dolibarr core code with no need to patch Dolibarr.
Hooks es una funcionalidad de desarrollo que permite a los desarrolladores agregar código personalizado en el código del núcleo de Dolibarr sin necesidad de parchear Dolibarr.
On the contrary to the triggers (another feature to interact with Dolibarr code) which are by definition linked to a business action, hooks can happen anywhere at anytime, they are an entry point into the program.
Al contrario que los triggers (otra funcionalidad para interactuar con el código de Dolibarr) que están vinculados a una acción de negociado, los hooks pueden producirse en cualquier lugar y en cualquier momento, son un punto de entrada en el programa.
* Hooks work by context (ie the module, eg: "productcard" for products, "invoicecard" for invoices, etc..). It's easy to find them, just search for "'''callHooks('''"
* Hooks trabaja por contexto (es decir por módulo, ej: "productcard" para productos, "invoicecard" para facturas, etc.). Es fácil de encontrar, solo hay que burcar por "'''callHooks('''"
* Hooks are functions that can be overloaded by your own. You decide if your code is added to standard Dolibarr code or if it replace Dolibarr code. You can find overloadable functions by searching for "'''executeHooks('''"
* Hooks son funciones que pueden ser sobrecargadas por las suyas  propias. Usted es el que decide si su código se añade al código estandar de Dolibarr o si reemplaza al código de Dolibarr. Puede encontrar funciones sobrecargables buscando por "'''executeHooks('''"




= Implementation =
= Implementaición =


To use a hook (overload a function), you first need to already have defined a module (see the wiki for that), and then you need to do 2 things:
Para usar un hook (sobrecarga de una función), debe de haber definido un módulo antes (vea la wiki para ello), y entonces tiene que hacer 2 cosas:


1- to add your module to the hooks of the context you want to hook on.
1- Añadir su módulo a los hooks del contexto que desee.
This means that when this context (module) will happen, your module will be called.
Esto significa que cuando este contexto (módulo) va a suceder, el módulo será llamado.
To do that, just edit your /htdocs/includes/modYourModuleName.class.php and edit the $this->const variable with something like this:
Para ello edite su /htdocs/includes/modSuModulo.class.php y edite la variable $this->const con algo como esto:


<source lang="php">
<source lang="php">
$this->const = array(  
$this->const = array( 0=>array('MAIN_MODULE_SUMODULO_HOOKS', 'chaine', 'productcard:invoicecard:propalcard', 'Hooks list for managing printing functions of the CustomFields module', 0);
                    0=>array('MAIN_MODULE_YOURMODULENAME_HOOKS', 'chaine', 'productcard:invoicecard:propalcard', 'Hooks list for managing printing functions of the CustomFields module', 0;  
</source>
</source>


Of course change YourModuleName with your own module's name.
Por supuesto, cambie SuModulo por el nombre de su módulo.
Don't touch 'chaine' which defines the type of the constant.
No toque 'chaine': define el tipo de la constante.
Then you get the value at the third index, which is a string with contexts separated by a comma.
Entonces obtendrá un valor en el tercer índice, una cadena con los contextos separados por una coma.


'''IMPORTANT''': Be careful: do not forget to DISABLE then RENABLE the module in the admin panel to accept the now const values, because these constants are only added to the database when enabling the module.
'''IMPORTANTE''': Tenga cuidado: No olvide DESACTIVAR y luego ACTIVAR el módulo en el panel de administración para aceptar los nuevos valores de las constantes, ya que estas constantes solo se añaden a la base de datos cuando se activa el módulo.


And please note that the const are updated because there is the remove() function (in the same file) that tells Dolibarr to remove the constants when disabling the module, else Dolibarr would not update the constants if they were not removed first (even if the values changed). Your remove() function should be something similar to this:
Y tenga en cuenta que la constante se actualiza porque se encuentra en la función remove() del mismo archivo, que le dice a Dolibarr que elimine las constantes en la desactivación del módulo, de lo contrario Dolibarr no actualiza las constantes si no se elimina primero (incluso si los valores han cambiado). Su función remove() debería ser algo similar a esto:


<source lang="php">
<source lang="php">
/**
/**
* Function called when module is disabled.
* Function called when module is disabled.
*             Remove from database constants, boxes and permissions from Dolibarr database.
* Remove from database constants, boxes and permissions from Dolibarr database.
* Data directories are not deleted.
* Data directories are not deleted.
*     @return    int            1 if OK, 0 if KO
* @return    int            1 if OK, 0 if KO
*/
*/
function remove()
function remove()
{
{
$sql = array("DELETE FROM ".MAIN_DB_PREFIX."const WHERE name like '%_mymodulename' OR name like '%_mymodulename_%';");
$sql = array("DELETE FROM ".MAIN_DB_PREFIX."const WHERE name like '%_mymodulename' OR name like '%_mymodulename_%';");
 
return $this->_remove($sql);
return $this->_remove($sql);
}
}
</source>
</source>


2- You will overload a hook (a function) with your own.
2- Sobrecargar un hook (una función) con la suya propia.


Create the file /htdocs/yourmodulename/class/actions_yourmodulename.class.php and then put something like this:
Cree un archivo '''/htdocs/''sumodulo''/class/actions_''sumodulo''.class.php''' y luego escriba algo como esto:


<source lang="php">
<source lang="php">
/**
*      \class      actions_yourmodulename
*      \brief      Example hook file
*/
class ActionsYourModuleName // extends CommonObject  
class ActionsYourModuleName // extends CommonObject  
{  
{  
Line 62: Line 55:
     *  @return      void  
     *  @return      void  
     */  
     */  
     function doActions($parameters, $object, $action) {  
     function doActions($parameters, $object, $action)  
    {  
         print_r($parameters);  
         print_r($parameters);  
         echo "action: ".$action;  
         echo "action: ".$action;  
         print_r($object);  
         print_r($object);  
   
   
         if ($parameters->context == 'somecontext') {  
         if ($parameters->context == 'somecontext')  
           // do something only for the context 'somecontext'}  
        {  
           // do something only for the context 'somecontext'
        }
    }
}  
</source>
</source>


where
donde
* $parameters is an array of meta-data about the datas contained by the hook (eg: the context, always accessible by $parameters->context).
* '''$parameters''' es un array de meta-datos acerca de los datos contenidos en el hook (ej: el contexto, siempre accesible mediante $parameters->context).
* $object is the object that you may work on. Eg: the product if you are in the productcard context.
* '''$object''' es el objeto con el que va a trabajar. Ej: el producto si se encuentra en el contexto productcard.
* $action is the action if one is conveyed (generally "create", "edit" or "view").
* '''$action''' es la acción si se ha enviado alguna (generalmente "create", "edit" o "view").
 
Su función debería llamarse cuando se acceda al módulo/contexto y podrá ver los parámetros, el objeto y la acción.


Your function should now be called when you access the module/context and you will see the parameters and object and action.
= Listado de Hooks disponibles =
{{ToComplete}}
* '''formObjectOptions''': llamado cada vez que los campos asociados al objeto principal son impresos o introducidos (ej: creation form, datasheet, edit form, etc.).


= List of available Hooks =
¿Cómo encontrar hooks disponibles?  
How to find the available hooks ?  
Realice una búsqueda de "'''executeHooks('''" y le será fácil encontrar las llamadas a los métodos Hook.
Just search for "'''executeHooks('''" and you should easily find all the hooked methods call.

Navigation menu