Module development

From Dolibarr Wiki

Return to developer
documentation index

To create a new module/addon for Dolibarr, there is several steps. This tutorial will describe you each of them to build a module to extend Dolibarr features, like one or several of the following :

  • Add new tables in database
  • Add your own menu entries
  • Add new screens to edit new tables
  • Add predefined exports for the internal export tool
  • Add new information boxes in the home page
  • Define new permissions
  • Execute code automatically triggered by a particular Dolibarr action

etc... All those operations are possible with version 2.4 or more of Dolibarr.

Following chapters presents how to do all of this manually with an easy way. For experienced developers, a method to do this using MDA generation is also on the work. See last chapter for this.

Contents

File:Art.png Create a descriptor of Module (required)

When: Required as soon as an addon is developed, whatever is its goal.

Create your module descriptor

The first step is to create a file descriptor for the module. To do this go into the directory dev/skeletons and copy the file modMyModule.class.php in the directory htdocs/includes/modules. Then change the contents of this file to replace:

  • all "modMyModule" with a value which corresponds to the vocation of your module. This value must always start with 'mod'.

WARNING: The MyModule MUST be set to a serie of alpha character, but the only character permit are [A-Za-z] and the MAX len of the XXX is 12 characters. In the 2.9 version will be add the support of the character "_" in the class name and the character permit will be [A-Za-z_].

  • $this->numero = 10000 by a number of free module (Go to Home page -> System Information -> Dolibarr -> Modules to know id the list of modules used).
  • Modify any other variables defined in the constructor (see comment in the code skeleton for their meaning).
  • Create directory /htdocs/mymodule/

Your file descriptor for your module is ready.

Test your descriptor

Launch Dolibarr and go to page Setup->module? You must see a new line with your new module and the possibility to activate it or not (browse all the tabs of each category of modules to find it). It's value of $this->special that determines in which tab will be your module.

File:Art.png Tree of path for new module files (required)

Create a directory 'mymodule' that will receive all files of your module. This directory must be inside the htdocs directory and will contains following subdirectories: File:Arbo_module.png

File:Art.png Create your SQL tables and the PHP accessor class (optional)

When: If your module needs to manage data of its own

Create your .sql file

If your module is designed to manage data of its own, which are not available in the standard version of Dolibarr, it is necessary to define SQL tables to store the data.

Files for your own module must be placed in a directory.

Create a subdirectory called "sql" into directory of your module (eg htdocs/mymodule/sql) to put the sql scripts that you will create. Then in the "load_tables" function of your file descriptor module, modify the line

$dir = DOL_DOCUMENT_ROOT.'/mymodule/sql/';

by

$dir = DOL_DOCUMENT_ROOT.'/valuechooseformymodule/sql/';

Rules to follow:

  • Add the files about creating tables commands on the principle of a file llx_matable.sql per table with a possibly file llx_matable.key.sql (see existing files in includes/mysql/tables for examples).
  • To manage data, you must create a file called data.sql inside directory /mymodule/sql/ that contains SQL command to add/edit/delete datas.

Example of content of a file data.sql

 DELETE FROM llx_const WHERE name='MYMODULE_IT_WORKS' AND entity='__ENTITY__';
 INSERT INTO llx_const (name, value, type, note, visible, entity) VALUES ('MYMODULE_IT_WORKS','1','chaine','A constant vor my module',1,'__ENTITY__');

Files must be operational for the database mysql. Rem: The files of other databases are not maintained. They will be read and converted on the fly by the driver of the other database.

Test your .sql files

Once the files ready, you can return to Dolibarr to disable the module, dropper tables in database and reactivate the module. The tables should be recreated by the activation of the module. If this is not the case, check your scripts by passing them by hand, or check the Dolibarr logs.

Generate the accessors PHP class (DAO)

Once you have created your tables into the database, move to the dev/skeletons directory and run the script

php build_class_from_table.php tablename

Note: If the command does not work, try to use php-cli php instead.

This will generate a file out.tablename.class.php that contains the class to manage table tablename. In this class, you can find the CRUD methods (Create / Read / Update / Delete) already working to do an insert, a fetch (select), an update, a delete of a row in table. Remove just the "out" from the file name and put the file in a subdirectory of htdocs specific to your module (in htdocs/mymodule for example).

A file out.tablename_script.php has been generated and contains a sample code to use the class for each of the 4 CRUD methods.

File:Art.png Add your own tabs on element sheets (optional)

When: To add a tab on an element (invoices, orders, proposals, member ...)

To do this go into the file descriptor of module previously created and edit the $this->tabs array:

	// Array to add new pages in new tabs
	$this->tabs = array('element:TabTitle:@mymodule:/mymodule/mynewpage.php?id=__ID__');
	// where element can be
	// 'thirdparty'       to add a tab in third party view
	// 'intervention'     to add a tab in intervention view
	// 'supplier_order'   to add a tab in supplier order view
	// 'supplier_invoice' to add a tab in supplier invoice view
	// 'invoice'          to add a tab in customer invoice view
	// 'order'            to add a tab in customer order view
	// 'product'          to add a tab in product view
	// 'propal'           to add a tab in proposal view
	// 'member'           to add a tab in foundation member view

The table should contain a list of strings, each string representing a new tab. The format of the string consisting of 4 parts separated by ":"

  • Part 1: The element code which should appear in the tab is a value from the following:
    • 'thirdparty'
    • 'intervention'
    • 'supplier_order'
    • 'supplier_invoice'
    • 'invoice'
    • 'order'
    • 'product'
    • 'propal'
    • 'member'
  • Part 2: The title of the tab. This can be a hard read or better code translation in a file lang.
  • Part 3: The name of the file. Lang which contains correspondence between the code translation and language to display. If this name start with @, Dolibarr will search translation file into the lang file of module, so htdocs/mymodule/langs/code_CODE/mymodule.lang, otherwise Dolibarr will look for file htdocs/langs/code_CODE/mymodyle.lang
  • Part 4: The url of the page to display when you click on the tab. The __ID__ string will be replaced automatically by the Id of the element concerned.

To feed the contents of the tab with data from the database, see the next chapter.

File:Art.png Create your own PHP screens (optional)

When: If the purpose of your module is to add features that require new screens.

Create a PHP screen

You must then create your PHP pages that will show/edit data from tables using the skeleton templates provided as an example in the directory dev/skeletons (For the development of a script from the command line, see Script development).

To create a new user screen, create a subdirectory of htdocs (if not already done) for your module (in htdocs/monmodule for example) to store the pages you will create.

Copy, into that directory, the file skeletons_page.php that will serve as a starting point for your page file. Edit the file to have a correct relative path to the main.inc.php file.

include("../../main.inc.php)";

This depends on the depth of the directory in which the file is (Add or remove "../"). It's in the main.inc.php file that is loaded technical environment variables and permissions. The following variables are objects positioned in this file:

  • $user Objet that contains the characteristics of the user + his permissions.
  • $conf Objet that contains Dolibarr configuration.
  • $db Objet that contains an opened connection handler to the database.
  • $langs Objet that contains the user's language.

Then enter your code to display the page.

Database access

If you need to edit some data in database inside you own table, use the PHP class generated before.

If you to make access to tables with no dedicated PHP class available, this is always possible (for example if you want to get a list of records with a particular join or filter). In this case, this is a code samples to follow:

To make an insert, update or delete:

$db->begin();   // Start transaction
$db->query("My SQL request insert, update or delete");
$db->commit();       // Validate transaction
or $db->rollback()  // Cancel transaction

To read:

$resql=$db->query("My select request");
if ($resql)
{
	$num = $db->num_rows($resql);
	$i = 0;
	if ($num)
	{
		while ($i < $num)
		{
			$obj = $db->fetch_object($resql);
			if ($obj)
			{
				// You can use here results
				print $obj->field1;
				print $obj->field2;
			}
			$i++;
		}
	}
}

Define style of your pages

To have the look of your own pages to match the Dolibarr theme, it is necessary to use the Dolibarr CSS styles.

You can use for example:

  • class="liste_titre" on tags tr and td for the head row of a table.
  • class="pair" or class="impair" on tags tr and td of other rows of a table.
  • class="flat" on all input fields (input, select, textarea...).
  • class="button" on HTML fields with type input type="submit".

Use the Dolibarr date picker

If you want to use the Dolibarr date selector (with its calendar popup) into your pages, use the following line:

 $form=new Form($db);
 $form->select_date('','mykey',0,0,0,"myform");

The string mykey will identify the date selector in the form. You must use different values if you use several date selectors in same page. The string myform is the name of the FORM in which the selector is included (value found in the form name="myform" in HTML page). This means a date selector must be included necessarily into an html FORM.

To get value after the POST of your form, the command is:

$mydate = dol_mktime(12, 0 , 0, $_POST['mykeymonth'], $_POST['mykeyday'], $_POST['mykeyyear']);
print strftime('%A %d %B %Y', $mydate);

File:Art.png Add your own setup page (optional)

When: If your module need to ask user several parameters.

Create your page to edit parameters

If your module need several parameters to be setup, you must create a page to edit options (that will be saved into table llx_const). Create a page named mymodule_setuppage.php that show possibles options and update them into table from a form. It is a necessary to take an example from a page into directory /admin that will show you the way to read/save your parameter. Put this page into directory /admin. Then, into the descriptor file of your module, modify the variable config_page_url to set name of this PHP page (without the path that is not necesary if page is inside directory admin).

$this->config_page_url = array("mymodule_setuppage.php");

Test your page

Go into page Home->Setup->Modules, you should see a picture at the end of the line of your module to reach your setup page. Click on it, you should be able to view/edit parameters from your page.

File:Art.png Define your entries in menu (optional)

When: If you have created PHP pages, it is necessary that those pages can be reached from menu entries in Dolibarr menu.

Define your menu entries

For this, you must define into the module descriptor, the array this->menu that declare all menus added by your module. This array contains entries that will appear once your module is activated. The example module descriptor file modMyModule.class.php contains an example to declare a top menu and also its left menu entries.

This is the example of code to declare your own menu entries in a module descriptor file:

// Main menu entries
$this->menu = array();			// List of menus to add
$r=0;
 
// Add here entries to declare new menus
// Example to declare the Top Menu entry:
$this->menu[$r]=array(	'fk_menu'=>0,			// Put 0 if this is a top menu
			'type'=>'top',			// This is a Top menu entry
			'titre'=>'MyModule top menu',
			'mainmenu'=>'mymodule',
			'leftmenu'=>'1',		// Use 1 if you also want to add left menu entries using this descriptor. Use 0 if left menu entries are defined in a file pre.inc.php (old school).
			'url'=>'/mymodule/pagetop.php',
			'langs'=>'mylangfile',	// Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
			'position'=>100,
			'enabled'=>'1',			// Define condition to show or hide menu entry. Use '$conf->mymodule->enabled' if entry must be visible if module is enabled.
			'perms'=>'1',			// Use 'perms'=>'$user->rights->mymodule->level1->level2' if you want your menu with a permission rules
			'target'=>'',
			'user'=>2);				// 0=Menu for internal users, 1=external users, 2=both
$r++;
 
// Example to declare a Left Menu entry:
$this->menu[$r]=array(	'fk_menu'=>'r=0',		// Use r=value where r is index key used for the parent menu entry (higher parent must be a top menu entry)
			'type'=>'left',			// This is a Left menu entry
			'titre'=>'MyModule left menu 1',
			'mainmenu'=>'mymodule',
			'url'=>'/mymodule/pagelevel1.php',
			'langs'=>'mylangfile',	// Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
			'position'=>100,
			'enabled'=>'1',			// Define condition to show or hide menu entry. Use '$conf->mymodule->enabled' if entry must be visible if module is enabled.
			'perms'=>'1',			// Use 'perms'=>'$user->rights->mymodule->level1->level2' if you want your menu with a permission rules
			'target'=>'',
			'user'=>2);				// 0=Menu for internal users,1=external users, 2=both
$r++;

To show menu or not depending on a permission, modify property perms in array. See chapter on permissions later to see how to add permissions.

Test your menu entries

Disable and reenable your module under Dolibarr module setup page, menus entries must appear (if property 'enabled' is declaration array is ok).

File:Art.png Add your own permissions (optional)

When: If you want to add new permissions.

The way to define permissions that will manage your module is done inside the module descriptor created previously. Modify line

$this->rights_class = 'mymodule'

with correct value for mymodule.

Then you must fill the array $this->rights with as many entries than different permissions you need to manage.

$this->rights[$r][0] = 10001;
$this->rights[$r][1] = 'Label by default of permission';
$this->rights[$r][3] = 1;
$this->rights[$r][4] = 'action';
$this->rights[$r][5] = 'subaction';
$r++;

Into $this->rights[$r][0], put a permission id not already used (See into menu System info on a working installation of Dolibarr to know list of id already used by standard modules. Into $this->rights[$r][3], put 1 if this permission must be granted automatically by default to any new created user. Into $this->rights[$r][1], put a label by default for permission (This label will be used if no translation can be found into the file admin.lang). Into $this->rights[$r][4] and $this->rights[$r][5], put an action and subaction string without spaces. You will be able to test if a user has the permission in your PHP source code with the sequence:

if ($user->rights->mymodule->action->subaction) ...

File:Art.png Define you own box (optional)

When: If your module need to provide one or several new boxes to show on home page.

Define your box

For this, modify the array $this->boxes into the module descriptor file. All you have to do is to add one line for each box file you will create into directory htdocs/includes/boxes

Example:

this->boxes[0][1]='mybox0.php'
this->boxes[1][1]='mybox1.php'
this->boxes[2][1]='mybox2.php'
...
this->boxes[n][1]='myboxn.php'

Then create files mybox0.php, mybox1.php... by copying an example from an existing box file (into directory htdocs/include/boxes).

Test if your box is detected by Dolibarr

Disable and enabled module.

Go into menu Home - Setup - Boxes.

Your boxes must appear in the list of boxes you can activated. Activate the box and go on home page to see if the box is showing correctly.

File:Art.png Define your own export (optional)

When: If your module provide new predefined database export profiles (for its own tables or for already existing tables of another module).

Define export

For this uncomment and modify arrays $this->export_xxx in your module descriptor file.

Test your export

Go into menu Tools -> Export. Your export will appear in the list of available predefined exports (if your module is enabled). Choose it, you must see list of all possible fields defined in the export arrays. Choose on field and try to build an export file. If ok, try again with all fields.

File:Art.png Define your CSS styles (optional)

When: If in your PHP pages, you use class styles that are not defined inside Dolibarr themes CSS (not recommanded).

Create and declare your style sheet

Create a style sheet CSS named mymodule.css and put it into directory htdocs/mymodule. You can have only one CSS file per module. Remember it's better to use existing styles already available by default into Dolibarr (The CSS file used by Dolibarr is file themes/mytheme/themename.php.css. Create your own CSS file only if you need absolutely to add not already existing styles. Once your style sheet is ready, declare it into your module descriptor file by modifying the property $this->style_sheet. Value to put here must be a relative URL to your CSS file. For example '/mymodule/myfile.css'.

Test your style sheet

Disable and enable your module.

Go on home page (index.php). Show the HTML source of the page.

You should see into the HTML header, a line that declare your style sheet.

File:Art.png Define you Javascript functions (optional)

When: If in your PHP pages, you use javascript functions not available in Dolibarr (in file lib_head.js)

If you need to use your own javascript functions inside your PHP pages, it is necessary to have your functions defined into a javascript file mymodule.js to be included inside the HTML HEAD section. To ask Dolibarr that forge this header to include your own javascript file, you must just declare your file inside the module descriptor.

This feature is not yet available.

File:Art.png Run your own code on any Dolibarr event (optional)

When: If you want to execute your own code once a common Dolibarr event has occurred (example: I want to update a table in my module when an invoice is created into Dolibarr), you must create a triggers.

See also Interfaces_Dolibarr_toward_foreign_systems and Interfaces_from_foreign_systems_toward_Dolibarr

File:Art.png Create a package to distribute and install your module

  • Go into the directory /build and copy the file makepack-dolibarrmodules.conf into makepack-mymodule.conf. Warning, this directory may not be provided in some packages of stable versions. If so, it can be retrieved from the CVS snapshot available for download on the Dolibarr website in area "Development version" (taken in this case the whole build directory which is autonomous and independent directory).

Edit this file to add list of file names for all new files you created for your module (module descriptor, new sql tables files, php page, images, etc...)

  • Run the script via Perl (need the Perl version 5.0 or later):
perl makepack-dolibarrmodule.pl

The script asks you the name of your module, its major and minor version. A file mymodule.tgz will then be manufactured containing your module ready to be deployed.

  • The person who receives your module must then place the file in the root directory of a Dolibarr installation and perform the command:
tar -xvf monmodule.tgz
  • If you want your module to be public, you can submit it (the tgz file) on Dolibarr web site on download area: DoliStore.com (you must create an account first and be logged to use the link "Submit a product").
    • If your module was build correctly, file will be validated later.
    • If quality is enough and license permits it, code might be added inside main Dolibarr sources (except if you disagree for that).

File:Art.png Some coding rules

The coding rules to be followed are defined in the Developer documentation, under section "General Information - Language and standards development".

File:Art.png Using MDA

A method to generate a functional module from a UML model has been developed. More information on the page UML2Dolibarr - Build a module using MDA.

Personal tools
In other languages
FrenchSpanish