Changes

Added llx_element_element php code example
Line 136: Line 136:     
Thank's to manub for giving this case.
 
Thank's to manub for giving this case.
 +
 +
= Linking Dolibarr objects from two different modules =
 +
 +
Dolibarr sometimes offers the possibility to link two different modules. Eg: when you convert an Intervention card into an Invoice.
 +
 +
In this case, you might want in your templates to fetch the custom fields of the linked object. Eg: you generate a PDF from the Invoice, but you want to get the custom fields from the Intervention that was converted into the Invoice.
 +
 +
The key here is to use the '''llx_element_element''': this is a standard Dolibarr table that stores all links between objects of two different modules.
 +
 +
Here is the structure:
 +
<pre>
 +
rowid | fk_source | sourcetype | fk_target | targettype
 +
-------------------------------------------------------
 +
1 | 2 | fichinter | 5 | facture
 +
</pre>
 +
 +
You can then use a php code like the following to populate your $object with customfields:
 +
<source lang="php">
 +
// Init and main vars for CustomFields
 +
dol_include_once('/customfields/lib/customfields_aux.lib.php');
 +
 +
// Filling the $object with customfields (you can then access customfields by doing $object->customfields->cf_yourfield)
 +
// This will also create and returns us an instance of the CustomFields class, which we will use to manually query the llx_element_element table
 +
$customfields = customfields_fill_object($object, null, $outputlangs, 'facture', true); // beautified values
 +
 +
// Querying the llx_element_element table manually to get the link between the invoice and the linked intervention card (we want the id of the intervention card)
 +
// fetchAny($columns, $table, $where='', $orderby='', $limitby='')
 +
$eltrow = $customfields->fetchAny('*', MAIN_DB_PREFIX.'element_element', 'fk_target='.$object->id);
 +
 +
// Save the intervention's id
 +
$sourceid = $eltrow[0]['fk_source'];
 +
 +
// Crafting a dummy intervention object
 +
$fromobject = object(); // Init the object
 +
$fromobject->id = $sourceid; // We need the id and..
 +
$fromobject->table_element = 'fichinter'; // the table_element (name of the table)
 +
 +
// We can then fill $object with the intervention custom fields (we store them in a sub property 'fichinter' to avoid conflicts with invoice's custom fields)
 +
customfields_fill_object($object, $fromobject, $outputlangs, 'fichinter', true);
 +
 +
// Now you can access invoices custom fields using:
 +
print($object->customfields->facture->cf_myfield);
 +
// And access intervention custom fields with:
 +
print($object->customfields->fichinter->cf_myfield);
 +
</source>
 +
 +
Thank's to netassopro for the tip.
439

edits