Script development
Location
The Dolibarr command line scripts must be located in the scripts directory in Dolibarr root. The scripts are then divided into sub-directories according to their vocation. A number of scripts is provided as standard.
Develop a new script
The scripts are often made for a specific need, it is likely that you do not find the one you want. In this case, we'll explain how to develop your own script.
Step 1 - Create the skeleton of the script
The first step is to take the skeleton script available in dev/skeletons/skeleton_scripts.php and copy and renaming it in directory scripts/mydir/myscript.php
Once renaming is done, give it permissions to execute. On linux, this is the command:
cd scripts/mydir;
chmod a+rx myscript.php
Then, run it to see if you can run the script in a command line mode. For this, on Linux, type:
php-cli ./myscript.php
or
php ./myscript.php
You must get the following output:
Usage: myscript.php param1 param2 ...
Step 2 - Editing script code
Modify the contents of the script to perform operations that interest you. All the code that lies between the tags
// ---------- START OF YOUR CODE HERE
and
// ---------- END OY YOUR CODE
is provided as an example. You can delete it and put the code that you want. Note that in this section, you can use the variable $db that is the resource to access Dolibarr database and is already initialized. The $conf object that contains Dolibarr configuration is also available.
Example to insert a product
For example to insert a product in the database Dolibarr, you can place the following code:
// Include mother classes for user and product
require_once(DOL_DOCUMENT_ROOT."/user.class.php");
require_once(DOL_DOCUMENT_ROOT."/product.class.php");
// Create a new user instance
$user=new User($db);
// Create a new product instance
$myproduct=new Product($db);
// Define properties of user
$user->id = 0;
// Define properties of product
$myproduct->ref = '1234';
$myproduct->libelle = 'libelle';
$myproduct->price = '10';
$myproduct->price_base_type = 'HT';
$myproduct->tva_tx = '19.6';
$myproduct->type = 0;
$myproduct->status = 1;
$myproduct->description = 'Description';
$myproduct->note = 'Note';
$myproduct->weight = 10;
$myproduct->weight_units = 0;
// Create product in database
$idproduct = $myproduct->create($user);
// Error management
if ($idproduct < 0) dol_print_error($db,$myproduct->error);
else print "Product $idproduct created.\n";