21require
'../../../../main.inc.php';
31if ($user->socid > 0) {
36require_once DOL_DOCUMENT_ROOT .
'/admin/tools/ui/class/documentation.class.php';
39$langs->load(
'uxdocumentation');
43$group =
'UxDolibarrContext';
44$experimentName =
'UxDolibarrContextHowItWork';
47 '/includes/ace/src/ace.js',
48 '/includes/ace/src/ext-statusbar.js',
49 '/includes/ace/src/ext-language_tools.js',
54$documentation->docHeader($langs->trans($experimentName, $group), $js, $css);
57$documentation->view = [$group, $experimentName];
60$documentation->showSidebar(); ?>
62<div
class=
"doc-wrapper">
64 <?php $documentation->showBreadCrumb(); ?>
66 <div
class=
"doc-content-wrapper">
68 <h1
class=
"documentation-title"><?php echo $langs->trans($group); ?> : <?php echo $langs->trans(
'UxDolibarrContextHowItWork'); ?></h1>
70 <?php $documentation->showSummary(); ?>
72 <div
class=
"documentation-section">
73 <h2
id=
"titlesection-basicusage" class=
"documentation-title">Introduction</h2>
76 DolibarrContext is a secure global JavaScript context
for Dolibarr.
77 It provides a single global object <code>window.Dolibarr</code>, which cannot be replaced.
78 It allows defining non-replaceable tools and managing hooks/events in a modular and secure way.
82 This system is designed to provide
long-term flexibility and maintainability. You can define reusable tools
83 that encapsulate functionality such as standardized AJAX requests and responses, ensuring consistent data handling across Dolibarr modules.
84 For example, tools can be created to wrap API calls and automatically process returned data in a uniform format,
85 reducing repetitive code and preventing errors.
89 Beyond DOM-based events, DolibarrContext allows monitoring and reacting to business events
using a
90 hook-like mechanism. For instance, you can listen to events such as
91 <code>Dolibarr.on(
'addline:load:productPricesList',
function(data) { ... });</code>
92 without relying on DOM changes. This enables creating logic that reacts directly to application state changes.
96 Similarly, you can define tools that act as global helpers, like <code>Dolibarr.tools.setEventMessage()</code>.
97 This tool can display notifications (similar to PHP
's <code>setEventMessage()</code> in Dolibarr),
98 initially using jNotify or any other library. In the future, the underlying library can change without affecting
99 the way modules or external code call this tool, maintaining compatibility and reducing maintenance.
103 In summary, DolibarrContext provides a secure, extensible foundation for adding tools, monitoring business events,
104 and standardizing interactions across Dolibarr's frontend modules.
108 <div
class=
"documentation-section">
109 <h2
id=
"titlesection-console-help" class=
"documentation-title">Console help</h2>
112 Open your browser console with <code>F12</code> to view the available commands.<br/>
113 If the help does not appear automatically,
type <code>Dolibarr.tools.showConsoleHelp();</code> in the console to display it.
117 <div
class=
"documentation-section">
118 <h2
class=
"documentation-title">Dolibarr.log() and debugMode()</h2>
121 <code>Dolibarr.log()</code> is a lightweight logging utility provided by the Dolibarr JS context.
122 It does <strong>not</strong> replace <code>console.log()</code>, but it gives an important advantage:
123 you can enable or disable all logs globally using <code>Dolibarr.debugMode()</code>.
126 <h3>Why use Dolibarr.log() instead of console.log()?</h3>
128 <li>You can enable or disable logging dynamically from the browser console.</li>
129 <li>Avoid polluting the console
for end-users: logs appear only when debug mode is enabled.</li>
130 <li>Ideal
for module development:
switch between quiet mode and verbose mode instantly.</li>
131 <li>Useful in production debugging: you can activate logs without modifying any code.</li>
134 <h3>How it works</h3>
136 When <code>debugMode</code> is
disabled (
default state), calls to <code>Dolibarr.log()</code>
do nothing.
137 When enabled, <code>Dolibarr.log()</code> behaves like <code>console.log()</code>.
143 ' // Log something (will only appear if debug mode is ON)',
144 ' Dolibarr.log("My debug message");',
146 ' // Enable verbose logs',
147 ' Dolibarr.debugMode(true);',
149 ' // Disable logs again',
150 ' Dolibarr.debugMode(false);',
153 $documentation->showCode($lines,
'php');
158 <li><code>console.log()</code> → always prints messages, noisy, not controllable, but useful during
active development and debugging.</li>
159 <li><code>Dolibarr.log()</code> → prints messages only when debug mode is ON; fully controllable. Ideal
for Dolibarr core logs or when you want to keep logs available but silent in production.</li>
160 <li><code>Dolibarr.debugMode(
true)</code> → enable verbose logs, activating <code>Dolibarr.log()</code> output.</li>
161 <li><code>Dolibarr.debugMode(
false)</code> → disable all <code>Dolibarr.log()</code> output, silencing debug messages.</li>
167 <div
class=
"documentation-section">
168 <h2
id=
"titlesection-hooks" class=
"documentation-title">JS Dolibarr hooks</h2>
171 Dolibarr provides a hook system to allow modules and scripts to communicate with each other
172 through named events. There are two ways to listen to these events in JS:
173 <code>Dolibarr.on()</code> and <code>document.addEventListener()</code>.
176 <h3>Event listener example</h3>
178 You can use <code>Dolibarr.on()</code> to listen to a hook. The main difference with standard
179 document events is that the callback receives <strong>directly the data
object</strong> passed
180 when the hook is executed, without needing to access <code>e.detail</code>.
183 For backward compatibility and standard DOM integration, the same hook can also be caught
184 using <code>document.addEventListener()</code>, but in
this case the data is inside
185 <code>e.detail</code> and the
event name is prefixed by <code>Dolibarr:</code> so
for a hook named A
event name is <code>Dolibarr:A</code>
191 ' // Add a listener to the Dolibarr theEventName event',
192 ' Dolibarr.on(\'theEventName\', function(data) {',
193 ' console.log(\'Dolibarr theEventName\', data);',
196 ' // But this work too on document',
197 ' document.addEventListener(\'Dolibarr:theEventName\', function(e) {',
198 ' console.log(\'Dolibarr theEventName\', e.detail);',
202 $documentation->showCode($lines,
'php'); ?>
205 <h3>Practical usage</h3>
207 When Dolibarr is ready (DOM loaded and JS context initialized), you can
register your hooks
208 or trigger them. Both <code>Dolibarr.on()</code> and <code>document.addEventListener()</code>
209 are valid, but <code>Dolibarr.on()</code> is simpler and more convenient because you
get the
215 ' document.addEventListener(\'Dolibarr:Ready\', function(e) {',
216 ' // the dom is ready and you are sure Dolibarr js context is loaded',
221 ' // Add a listener to the yourCustomHookName event with dolibarr.on()',
222 ' Dolibarr.on(\'yourCustomHookName\', function(data) {',
223 ' console.log(\'With Dolibarr.on : data will contain { data01: \'stuff\', data02: \'other stuff\' }\', data);',
226 ' // Or you can do : Add a listener to the yourCustomHookName document.addEventListener()',
227 ' document.addEventListener(\'Dolibarr:yourCustomHookName\', function(e) {',
228 ' console.log(\'With document.addEventListener : e.detail will contain { data01: \'stuff\', data02: \'other stuff\' }\', e.detail);',
231 ' // you can trigger js hooks',
232 ' document.getElementById(\'try-event-yourCustomHookName\').addEventListener(\'click\', function(e) {',
233 ' Dolibarr.executeHook(\'yourCustomHookName\', { data01: \'stuff\', data02: \'other stuff\' })',
243 $documentation->showCode($lines,
'php'); ?>
245 <div
class=
"documentation-example">
246 Open your console <code>F12</code> and click on <
button class=
"button" id=
"try-event-yourCustomHookName">
try</
button>
247 <script nonce=
"<?php print getNonce() ?>" >
248 document.addEventListener(
'Dolibarr:Ready',
function(e) {
251 Dolibarr.on(
'yourCustomHookName',
function(data) {
252 console.log(
'With Dolibarr.on : data will contain { data01: stuff, data02: other stuff }', data);
255 document.addEventListener(
'Dolibarr:yourCustomHookName',
function(e) {
256 console.log(
'With document.addEventListener : e.detail will contain { data01: stuff, data02: other stuff }', e.detail);
259 document.getElementById(
'try-event-yourCustomHookName').addEventListener(
'click',
function(e) {
261 Dolibarr.executeHook(
'yourCustomHookName', { data01:
'stuff', data02:
'other stuff' })
273 <div
id=
"titlesection-event-init-vs-ready" class=
"documentation-section">
274 <h2
class=
"documentation-title">Difference between Dolibarr:Init and Dolibarr:Ready
event</h2>
277 Dolibarr provides two main initialization events
for its JavaScript context: <code>Dolibarr:Init</code> and <code>Dolibarr:Ready</code>.
278 Understanding their difference is important when developing modules or tools.
283 <strong>Dolibarr:Init</strong> is triggered immediately when the Dolibarr context is created.
284 This
event is intended
for:
286 <li>Defining or registering
new tools via <code>Dolibarr.defineTool()</code>.</li>
287 <li>Setting context variables (<code>Dolibarr.setContextVar()</code> / <code>Dolibarr.setContextVars()</code>).</li>
288 <li>Preparing configuration that must be available before the DOM is fully loaded.</li>
290 It occurs <em>before</em> <code>Dolibarr:Ready</code>, so it is ideal
for setup tasks that other tools may depend on.
294 <strong>Dolibarr:Ready</strong> is triggered once the DOM is ready, similar to <code>$(document).ready()</code> in jQuery.
295 This
event is intended
for:
297 <li>Running code that interacts with the DOM.</li>
298 <li>Attaching
event listeners to elements on the page.</li>
299 <li>Executing functionality that
requires all tools and context variables to be fully initialized.</li>
305 In short, use <code>Dolibarr:Init</code>
for setting up tools and context variables, and <code>Dolibarr:Ready</code>
for code that needs the DOM and fully initialized context.
308 <h3>Examples of usage</h3>
312 ' // Example: Dolibarr:Init - define a tool and set context variables early',
313 ' document.addEventListener(\'Dolibarr:Init\', function(e) {',
314 ' console.log("Init event fired, Dolibarr is initialised and receive context vars a tools");',
317 ' // Example: Dolibarr:Ready - interact with DOM and use tools',
318 ' document.addEventListener(\'Dolibarr:Ready\', function(e) {',
319 ' console.log("Ready event fired, DOM is ready");',
322 ' // Attach event listener to a DOM element',
323 ' const btn = document.getElementById("myButton");',
325 ' btn.addEventListener("click", function() {',
326 ' alert("Button clicked! Context value: " + Dolibarr.getContextVar("mySetting"));',
332 $documentation->showCode($lines,
'php'); ?>
338 <li><code>Dolibarr:Init</code> → early setup, tools, context variables, configuration.</li>
339 <li><code>Dolibarr:Ready</code> → DOM is ready, safe to manipulate elements and use tools defined in Init.</li>
344 <div
class=
"documentation-section">
345 <h2
id=
"titlesection-await-hooks" class=
"documentation-title">Async Hooks (Await Hooks) - sequential execution</h2>
348 Dolibarr supports <strong>asynchronous hooks</strong> using <code>Dolibarr.onAwait()</code> and <code>Dolibarr.executeHookAwait()</code>.
349 These hooks allow you to
register functions that execute <em>in sequence</em> and can modify data before passing it to the next hook.
350 They are useful
for complex workflows where multiple modules or scripts need to process or enrich the same data asynchronously.
354 Each hook can optionally specify <code>before</code> or <code>after</code> to control the execution order relative to other hooks.
355 Every hook registration returns a unique <code>
id</code>, which can be used to reference or unregister the hook later.
359 Unlike standard synchronous hooks registered with <code>Dolibarr.on()</code>, await hooks
return a <code>Promise</code> when executed.
360 This means you can <code>await</code> their results in your code, and any asynchronous operations inside a hook (e.g., API calls, timers) will be handled correctly before moving to the next hook.
365 '<script nonce="<?php print getNonce() ?>">',
366 ' document.addEventListener(\'Dolibarr:Ready\', async function(e) {',
368 ' // Register async hooks will be executed in first place',
369 ' Dolibarr.onAwait(\'calculateDiscount\', async function(order) {',
370 ' order.total *= 0.9; // Apply 10% discount',
372 ' }, { id: \'discount10\' });',
374 ' // Register async hooks will be executed in third place',
375 ' Dolibarr.onAwait(\'calculateDiscount\', async function(order) {',
376 ' if(order.total > 1000) order.total -= 50; // Extra discount over 1000',
378 ' }, { id: \'discountOver1000\', after: \'discount10\' });',
380 ' // Register async hooks will be executed in second place',
381 ' // this hook item as no id so plus10HookItemId will receive a unique random id ',
382 ' let plus10HookItemId = Dolibarr.onAwait(\'calculateDiscount\', async function(order) {',
383 ' order.newObjectAttribute = \'My value\';',
384 ' order.total += 10;',
386 ' }, { before: \'discountOver1000\' });',
388 ' document.getElementById(\'try-event-yourCustomAwaitHookName\').addEventListener(\'click\', async function(e) {',
389 ' // Execute all registered await hooks sequentially',
390 ' let order = {total: 1200};',
391 ' order = await Dolibarr.executeHookAwait(\'calculateDiscount\', order);',
392 ' console.log(order); // order.total : 1200 -> 1080 -> 1090 -> 1040',
398 $documentation->showCode($lines,
'php'); ?>
400 <div
class=
"documentation-example">
401 Open your console <code>F12</code> and click on <
button class=
"button" id=
"try-event-yourCustomAwaitHookName">
try</
button>
403 <script nonce=
"<?php print getNonce() ?>">
404 document.addEventListener(
'Dolibarr:Ready', async
function(e) {
407 Dolibarr.onAwait(
'calculateDiscount', async
function(order) {
410 }, { id:
'discount10' });
413 Dolibarr.onAwait(
'calculateDiscount', async
function(order) {
414 if(order.total > 1000) order.total -= 50;
416 }, { id:
'discountOver1000', after:
'discount10' });
419 Dolibarr.onAwait(
'calculateDiscount', async
function(order) {
420 order.newObjectAttribute =
'My value';
423 }, { before:
'discountOver1000' });
425 document.getElementById(
'try-event-yourCustomAwaitHookName').addEventListener(
'click', async
function(e) {
427 let order = {total: 1200};
428 order = await Dolibarr.executeHookAwait(
'calculateDiscount', order);
438 <div
class=
"documentation-section">
439 <h2
id=
"titlesection-dom-initnewcontent" class=
"documentation-title">
440 initNewContent
event system
444 The <strong>initNewContent</strong>
event is a standardized Dolibarr mechanism
445 to re-initialize UI components on dynamically added content.
446 Use it whenever you inject
new DOM elements via AJAX, templates, or other dynamic updates.
449 <h3
id=
"titlesection-usecase-tooltips" class=
"documentation-title">
450 Use Case example: Dynamic Tooltips
454 In a typical Dolibarr page, tooltips are initialized on page load
for all elements
455 that have the class <code>.classfortooltip</code>. This works perfectly
for static content.
459 However, when a section of the page is dynamically recreated or loaded via AJAX,
460 the
new elements with <code>.classfortooltip</code>
do not automatically have tooltips,
461 because the initialization script has already run on the initial DOM and is not rerun
for the
new elements.
465 The <strong>initNewContent</strong> mechanism solves
this problem by providing a standardized hook
466 to re-initialize all interactive components on newly added DOM elements.
467 Developers can listen to <code>initNewContent</code> and re-run tooltip initialization
468 (or any other dynamic behavior) only on the
new elements or their children, ensuring consistency and avoiding duplication.
472 This approach guarantees that tooltips, dialogs, and other interactive components
473 remain functional even when content is injected or updated asynchronously.
477 In addition to <code>document.ready</code> or <code>$(document).ready()</code>,
478 listen to <strong>initNewContent</strong> to ensure that tooltips, dialogs, or other interactive components
479 are properly initialized on any
new DOM fragment added dynamically.
483 <div
class=
"documentation-example">
485 <
button class=
"button" id=
"try-no-initNewContent">Test without
event</
button>
486 <
button class=
"button" id=
"try-initNewContent">Test with initNewContent
event</
button>
488 <div
id=
"initNewContent-test-container"></div>
492 @keyframes highlightfortest {
493 from { background-color: #fffa8d; }
494 to { background-color: transparent; }
498 animation: highlightfortest 1s ease-out;
501 <div
id=
"idfortooltiponclick_doc-event-dialog-test" class=
"classfortooltiponclicktext" title=
"The title" style=
"display: none" >Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce nec elit venenatis, bibendum dui in, tristique dolor. In hac habitasse platea dictumst. Vestibulum consectetur quam non felis fringilla mollis pretium vel nibh. Pellentesque congue risus et laoreet blandit. Aliquam orci ipsum, gravida
id leo eget, molestie pulvinar sem. Nulla sed felis et lacus tristique finibus. Cras ornare tincidunt. Aenean hendrerit volutpat efficitur. Integer vestibulum dui eget lectus pulvinar, vel mattis odio facilisis. Etiam convallis scelerisque lobortis. Mauris tristique, quam dignissim sollicitudin sodales, elit ligula venenatis neque, sit amet interdum lacus tellus
id tellus. Mauris eu pretium turpis. Proin porta sem eget nisl vulputate vehicula.</div>
502 <script nonce=
"<?php print getNonce() ?>">
503 document.addEventListener(
'Dolibarr:Ready',
function(e) {
504 const container = document.getElementById(
'initNewContent-test-container');
506 document.getElementById(
'try-no-initNewContent').addEventListener(
'click',
function() {
507 container.innerHTML = `<span
class=
"classfortooltip highlightfortest" title=
"this is the title">A text with a tooltip but the tooltip isn
't load</span>
508 and <span class="classfortooltiponclick highlightfortest" dolid="doc-event-dialog-test" style="cursor: pointer;" >A text with a tooltip to click but the tooltip isn't load</span>`;
511 document.getElementById(
'try-initNewContent').addEventListener(
'click',
function() {
512 container.innerHTML = `<span
class=
"classfortooltip highlightfortest" title=
"this is the title">A text with a tooltip and the tooltip is loaded</span>
513 And <span
class=
"classfortooltiponclick highlightfortest" dolid=
"doc-event-dialog-test" style=
"cursor: pointer;" >A text with a tooltip to click and the tooltip is loaded</span>`;
514 Dolibarr.initNewContent(container);
523 '<div id="idfortooltiponclick_doc-event-dialog-test" class="classfortooltiponclicktext" title="The title" >Lorem ipsum .....</div>',
524 '<script nonce="<?php print getNonce() ?>">',
525 'document.addEventListener("Dolibarr:Ready", function(e) {',
526 ' const container = document.getElementById("initNewContent-test-container");',
528 ' // Insert content without calling initNewContent',
529 ' document.getElementById("try-no-initNewContent").addEventListener("click", function() {',
530 ' container.innerHTML = `<span class="classfortooltip highlightfortest" title="this is the title">A text with a tooltip but the tooltip isn\'t load</span>',
531 ' and <span class="classfortooltiponclick highlightfortest" dolid="doc-event-dialog-test" style="cursor: pointer;">A text with a tooltip to click but the tooltip isn\'t load</span>`;',
534 ' // Insert content and trigger initNewContent',
535 ' document.getElementById("try-initNewContent").addEventListener("click", function() {',
536 ' container.innerHTML = `<span class="classfortooltip highlightfortest" title="this is the title">A text with a tooltip and the tooltip is loaded</span>',
537 ' and <span class="classfortooltiponclick highlightfortest" dolid="doc-event-dialog-test" style="cursor: pointer;">A text with a tooltip to click and the tooltip is loaded</span>`;',
538 ' Dolibarr.initNewContent(container);',
543 $documentation->showCode($lines,
'php'); ?>
545 <h3
id=
"titlesection-usecase-tooltips" class=
"documentation-title">
550 The
event handler receives an
object with the property <code>targets</code>,
551 which is an array of DOM elements or jQuery collections to initialize. Each element can be:
555 <li>a container with child elements to initialize</li>
556 <li>or a direct element that needs initialization</li>
559 <h4>Example: Trigger initNewContent manually on a container</h4>
563 '<script nonce="<?php print getNonce() ?>">',
564 ' document.addEventListener(\'Dolibarr:Ready\', function(e) {',
565 ' /* [... code that dynamically reloads part of the DOM ...] */',
568 ' * true: only include the children of each target element',
569 ' * false: include the target elements themselves',
571 ' const applyToChildrenOnly = true;',
573 ' // Trigger initNewContent manually on a jQuery container',
574 ' Dolibarr.initNewContent($("#myContainer"), applyToChildrenOnly);',
576 ' // Trigger initNewContent manually on a vanilla JS element',
577 ' const element = document.getElementById("myContainer");',
578 ' Dolibarr.initNewContent(element, applyToChildrenOnly);',
582 $documentation->showCode($lines,
'php'); ?>
585 Dolibarr provides a custom
event system to properly initialize dynamic content.
586 Always use <strong>initNewContent</strong> when working with AJAX-injected fragments or
587 dynamically created elements instead of relying solely on jQuery document ready.
592 <h4>Example in pure JS style: listening to initNewContent</h4>
595 '<script nonce="<?php print getNonce() ?>">',
596 ' Dolibarr.on("initNewContent", ({ targets }) => {',
597 ' targets.forEach(root => {',
599 ' // Array to store all matching dialog elements',
600 ' const dialogs = [];',
602 ' // Include the root element if it matches the selector',
603 ' if (root.matches(".classfortooltiponclicktext")) {',
604 ' dialogs.push(root);',
607 ' // Add all descendants matching the selector',
608 ' dialogs.push(...root.querySelectorAll(".classfortooltiponclicktext"));',
610 ' // Initialize each dialog element',
611 ' dialogs.forEach(el => {',
612 ' // Your code to initialize the tooltip/dialog or other stuff',
618 $documentation->showCode($lines,
'php');
621 <h4>Compact version in pure JS</h4>
624 '<script nonce="<?php print getNonce() ?>">',
625 ' Dolibarr.on("initNewContent", ({ targets }) => {',
626 ' targets.forEach(root => {',
627 ' const dialogs = [',
628 ' ...(root.matches(".classfortooltiponclicktext") ? [root] : []),',
629 ' ...root.querySelectorAll(".classfortooltiponclicktext")',
631 ' dialogs.forEach(el => {',
632 ' // Initialize tooltip/dialog or other stuff here',
638 $documentation->showCode($lines,
'php');
641 <h4>Example in jQuery style</h4>
644 '<script nonce="<?php print getNonce() ?>">',
645 ' Dolibarr.on("initNewContent", ({ targets }) => {',
646 ' targets.forEach($root => {',
647 ' const $dialogs = $root',
648 ' .filter(".classfortooltiponclicktext")',
649 ' .add($root.find(".classfortooltiponclicktext"));',
650 ' $dialogs.each(function () {',
651 ' const $el = $(this);',
652 ' // Initialize tooltip/dialog behavior or other stuff here',
658 $documentation->showCode($lines,
'php');
665 <div
class=
"documentation-section">
666 <h2
id=
"titlesection-create-tool-example" class=
"documentation-title">Example of creating a
new context tool</h2>
668 <h3>Defining Tools</h3>
670 You can define reusable and
protected tools in the Dolibarr context using <code>Dolibarr.defineTool</code>.
672 <p>See also <code>dolibarr-context.mock.js</code>
for defining all standard Dolibarr tools and creating mock implementations to improve code completion and editor support.</p>
673 <p><b>Note :</b> a tool can be a
class not only a function</p>
678 'document.addEventListener(\'Dolibarr:Init\', function(e) {',
679 ' // Define a simple tool',
680 ' let overwrite = false; // Once a tool is defined, it cannot be replaced.',
681 ' Dolibarr.defineTool(\'alertUser\', (msg) => alert(\'[Dolibarr] \' + msg), overwrite);',
684 'document.addEventListener(\'Dolibarr:Ready\', function(e) {',
686 ' Dolibarr.tools.alertUser(\'hello world\');',
690 $documentation->showCode($lines,
'php'); ?>
692 <h3>Protected Tools</h3>
694 Once a tool is defined on overwrite
false, it cannot be replaced. Attempting to redefine it without overwrite will
throw an error:
701 ' Dolibarr.defineTool(\'alertUser\', () => {});',
703 ' console.error(e.message);',
707 $documentation->showCode($lines,
'php'); ?>
709 <h3>Reading Tools</h3>
711 You can read the list of available tools using <code>Dolibarr.tools</code>. It returns a frozen copy:
717 ' console.log(Dolibarr.tools);',
718 ' if(Dolibarr.checkToolExist(\'Tool name to check\')){/* ... */}else{/* ... */}; ',
721 $documentation->showCode($lines,
'php'); ?>
725 <?php include __DIR__ .
'/inc_seteventmessage.php'; ?>
728 <div
class=
"documentation-section">
729 <h2
id=
"titlesection-contextvars" class=
"documentation-title">Set and use context vars</h2>
732 The <strong>
Context Vars</strong> system allows you to define and manage variables that are globally accessible within the Dolibarr JavaScript context. These variables can store configuration data, URLs, tokens,
user IDs,
object references, or any other values needed by your frontend code and tools.
733 By
using context vars, you can:
735 <li>Pass server-side data (from PHP) to JavaScript safely and consistently.</li>
736 <li>Provide reusable configuration
for Dolibarr tools, widgets, or modules without hardcoding values.</li>
737 <li>Define overridable or non-overridable vars to protect critical values
while allowing flexible overrides when necessary.</li>
738 <li>Use <code>Dolibarr.setContextVar</code>
for single values or <code>Dolibarr.setContextVars</code> to pass multiple values at once.</li>
739 <li>Access these variables anywhere in your code via <code>Dolibarr.getContextVar(key)</code>.</li>
740 <li>Ensure that all your modules and tools can rely on consistent and up-to-
date context information, improving maintainability and interoperability.</li>
742 This system is particularly useful
for setting up base URLs, API endpoints,
user-specific information, or runtime data that needs to be shared across multiple Dolibarr frontend tools.
745 <h3>Add context var (overridable or not)</h3>
748 '<script nonce="<?php print getNonce() ?>" >',
749 ' document.addEventListener(\'Dolibarr:Init\', function(e) {',
750 ' // Add no overridable context var',
751 ' Dolibarr.setContextVar(\'yourKey\', \'YourValue\');',
753 ' // Add overridable context var',
754 ' Dolibarr.setContextVar(\'yourKey2\', \'YourValue\', true);',
758 $documentation->showCode($lines,
'php');
762 <h3>Add multiple context vars (overridable or not)</h3>
766 ' $contextConst = [',
767 ' \'DOL_URL_ROOT\' => DOL_URL_ROOT,',
768 ' \'token\' => newToken(),',
769 ' \'cardObjectElement\' => $object->element,',
770 ' \'cardObjectId\' => $object->id,',
771 ' \'currentUserId\' => $user->id',
776 ' \'lastCardDataRefresh\' => time(),',
780 '<script nonce="<?php print getNonce() ?>" >',
781 ' document.addEventListener(\'Dolibarr:Init\', function(e) {',
782 ' Dolibarr.setContextVars(<?php print json_encode($contextConst); ?>);',
783 ' Dolibarr.setContextVars(<?php print json_encode($contextVars); ?>, true);',
787 $documentation->showCode($lines,
'php');
790 <h3>Get context var</h3>
793 '<script nonce="<?php print getNonce() ?>" >',
794 ' document.addEventListener(\'Dolibarr:Ready\', function(e) {',
795 ' let url = Dolibarr.getContextVar(\'DOL_URL_ROOT\', \'The optional fallback value\'));',
796 ' console.log(url);',
800 $documentation->showCode($lines,
'php');
815$documentation->docFooter();
Class to manage UI documentation.
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
$conf db user
Active Directory does not allow anonymous connections.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
$conf db name
Only used if Module[ID]Name translation string is not found.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.