dolibarr 25.0.0-alpha
index.php
1<?php
2/*
3 * Copyright (C) 2025 Anthony Damhet <a.damhet@progiseize.fr>
4 * Copyright (C) 2025-2026 Frédéric France <frederic.france@free.fr>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20// Load Dolibarr environment
21require '../../../../main.inc.php';
22
30// Protection if external user
31if ($user->socid > 0) {
33}
34
35// Includes
36require_once DOL_DOCUMENT_ROOT . '/admin/tools/ui/class/documentation.class.php';
37
38// Load documentation translations
39$langs->load('uxdocumentation');
40
41//
42$documentation = new Documentation($db);
43$group = 'UxDolibarrContext';
44$experimentName = 'UxDolibarrContextHowItWork';
45
46$js = [
47 '/includes/ace/src/ace.js',
48 '/includes/ace/src/ext-statusbar.js',
49 '/includes/ace/src/ext-language_tools.js',
50];
51$css = [];
52
53// Output html head + body - Param is Title
54$documentation->docHeader($langs->trans($experimentName, $group), $js, $css);
55
56// Set view for menu and breadcrumb
57$documentation->view = [$group, $experimentName];
58
59// Output sidebar
60$documentation->showSidebar(); ?>
61
62<div class="doc-wrapper">
63
64 <?php $documentation->showBreadCrumb(); ?>
65
66 <div class="doc-content-wrapper">
67
68 <h1 class="documentation-title"><?php echo $langs->trans($group); ?> : <?php echo $langs->trans('UxDolibarrContextHowItWork'); ?></h1>
69
70 <?php $documentation->showSummary(); ?>
71
72 <div class="documentation-section">
73 <h2 id="titlesection-basicusage" class="documentation-title">Introduction</h2>
74
75 <p>
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.
79 </p>
80
81 <p>
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.
86 </p>
87
88 <p>
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.
93 </p>
94
95 <p>
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.
100 </p>
101
102 <p>
103 In summary, DolibarrContext provides a secure, extensible foundation for adding tools, monitoring business events,
104 and standardizing interactions across Dolibarr's frontend modules.
105 </p>
106 </div>
107
108 <div class="documentation-section">
109 <h2 id="titlesection-console-help" class="documentation-title">Console help</h2>
110
111 <p>
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.
114 </p>
115 </div>
116
117 <div class="documentation-section">
118 <h2 class="documentation-title">Dolibarr.log() and debugMode()</h2>
119
120 <p>
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>.
124 </p>
125
126 <h3>Why use Dolibarr.log() instead of console.log()?</h3>
127 <ul>
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>
132 </ul>
133
134 <h3>How it works</h3>
135 <p>
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>.
138 </p>
139
140 <?php
141 $lines = array(
142 '<script>',
143 ' // Log something (will only appear if debug mode is ON)',
144 ' Dolibarr.log("My debug message");',
145 '',
146 ' // Enable verbose logs',
147 ' Dolibarr.debugMode(true);',
148 '',
149 ' // Disable logs again',
150 ' Dolibarr.debugMode(false);',
151 '</script>',
152 );
153 $documentation->showCode($lines, 'php');
154 ?>
155
156 <h3>Summary</h3>
157 <ul>
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>
162 </ul>
163
164 </div>
165
166
167 <div class="documentation-section">
168 <h2 id="titlesection-hooks" class="documentation-title">JS Dolibarr hooks</h2>
169
170 <p>
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>.
174 </p>
175
176 <h3>Event listener example</h3>
177 <p>
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>.
181 </p>
182 <p>
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>
186 </p>
187
188 <?php
189 $lines = array(
190 '<script>',
191 ' // Add a listener to the Dolibarr theEventName event',
192 ' Dolibarr.on(\'theEventName\', function(data) {',
193 ' console.log(\'Dolibarr theEventName\', data);',
194 ' });',
195 '',
196 ' // But this work too on document',
197 ' document.addEventListener(\'Dolibarr:theEventName\', function(e) {',
198 ' console.log(\'Dolibarr theEventName\', e.detail);',
199 ' });',
200 '</script>',
201 );
202 $documentation->showCode($lines, 'php'); ?>
203
204
205 <h3>Practical usage</h3>
206 <p>
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
210 data directly.
211 </p>
212 <?php
213 $lines = array(
214 '<script>',
215 ' document.addEventListener(\'Dolibarr:Ready\', function(e) {',
216 ' // the dom is ready and you are sure Dolibarr js context is loaded',
217 ' ...',
218 ' // Do your stuff',
219 ' ...',
220 '',
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);',
224 ' });',
225 '',
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);',
229 ' });',
230 '',
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\' })',
234 ' });',
235 '',
236 ' ...',
237 ' // Do your stuff',
238 ' ...',
239
240 ' });',
241 '</script>',
242 );
243 $documentation->showCode($lines, 'php'); ?>
244
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) {
249 // the dom is ready and you are sure Dolibarr js context is loaded
250 // Add a listener to the yourCustomHookName event
251 Dolibarr.on('yourCustomHookName', function(data) {
252 console.log('With Dolibarr.on : data will contain { data01: stuff, data02: other stuff }', data);
253 });
254
255 document.addEventListener('Dolibarr:yourCustomHookName', function(e) {
256 console.log('With document.addEventListener : e.detail will contain { data01: stuff, data02: other stuff }', e.detail);
257 });
258
259 document.getElementById('try-event-yourCustomHookName').addEventListener('click', function(e) {
260 // you can create js hooks
261 Dolibarr.executeHook('yourCustomHookName', { data01: 'stuff', data02: 'other stuff' })
262 });
263
264 });
265 </script>
266
267 </div>
268
269 </div>
270
271
272
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>
275
276 <p>
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.
279 </p>
280
281 <ul>
282 <li>
283 <strong>Dolibarr:Init</strong> is triggered immediately when the Dolibarr context is created.
284 This event is intended for:
285 <ul>
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>
289 </ul>
290 It occurs <em>before</em> <code>Dolibarr:Ready</code>, so it is ideal for setup tasks that other tools may depend on.
291 </li>
292
293 <li>
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:
296 <ul>
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>
300 </ul>
301 </li>
302 </ul>
303
304 <p>
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.
306 </p>
307
308 <h3>Examples of usage</h3>
309 <?php
310 $lines = array(
311 '<script>',
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");',
315 ' });',
316 '',
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");',
320 '',
321 '',
322 ' // Attach event listener to a DOM element',
323 ' const btn = document.getElementById("myButton");',
324 ' if(btn) {',
325 ' btn.addEventListener("click", function() {',
326 ' alert("Button clicked! Context value: " + Dolibarr.getContextVar("mySetting"));',
327 ' });',
328 ' }',
329 ' });',
330 '</script>',
331 );
332 $documentation->showCode($lines, 'php'); ?>
333
334
335 <p>
336 In summary:
337 <ul>
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>
340 </ul>
341 </p>
342
343 <h3 id="titlesection-late-scripts">Scripts loaded after Ready (sticky events)</h3>
344 <p>
345 <code>Init</code> and <code>Ready</code> are <strong>sticky</strong> events: a listener added with <code>Dolibarr.on()</code>
346 after they were executed (script loaded with ajax, lazy loaded module...) is called immediately with their data.
347 This is not possible with <code>document.addEventListener('Dolibarr:Ready')</code>: a DOM event is never replayed,
348 so prefer <code>Dolibarr.on()</code> or <code>Dolibarr.ready()</code>.
349 </p>
350 <ul>
351 <li><code>Dolibarr.ready(callback)</code> returns a promise resolved when the context is ready, even if called after the Ready event.</li>
352 <li><code>Dolibarr.whenTool(name, {timeout})</code> returns a promise resolved with the tool as soon as it is defined.</li>
353 <li><code>Dolibarr.on(name, callback, {once: true})</code> removes the listener after its first call.</li>
354 <li><code>Dolibarr.executeHook(name, data, {sticky: true})</code> makes your own one time event sticky (ex: your module is loaded).</li>
355 </ul>
356 <?php
357 $lines = array(
358 '<script>',
359 ' // Works before and after the Ready event',
360 ' Dolibarr.ready(function() {',
361 ' // DOM is ready, tools are defined',
362 ' });',
363 '',
364 ' // Or with await',
365 ' await Dolibarr.ready();',
366 '',
367 ' // Wait for a tool defined by another module, reject after 5 seconds',
368 ' const quickMemo = await Dolibarr.whenTool(\'quickMemo\', { timeout: 5000 });',
369 '',
370 ' // Make your own one time event sticky',
371 ' Dolibarr.executeHook(\'myModuleLoaded\', { version: \'1.0\' }, { sticky: true });',
372 '</script>',
373 );
374 $documentation->showCode($lines, 'php'); ?>
375 </div>
376
377 <div class="documentation-section">
378 <h2 id="titlesection-await-hooks" class="documentation-title">Async Hooks (Await Hooks) - sequential execution</h2>
379
380 <p>
381 Dolibarr supports <strong>asynchronous hooks</strong> using <code>Dolibarr.onAwait()</code> and <code>Dolibarr.executeHookAwait()</code>.
382 These hooks allow you to register functions that execute <em>in sequence</em> and can modify data before passing it to the next hook.
383 They are useful for complex workflows where multiple modules or scripts need to process or enrich the same data asynchronously.
384 </p>
385
386 <p>
387 Each hook can optionally specify <code>before</code> or <code>after</code> to control the execution order relative to other hooks.
388 Every hook registration returns a unique <code>id</code>, which can be used to reference or unregister the hook later.
389 </p>
390
391 <p>
392 Unlike standard synchronous hooks registered with <code>Dolibarr.on()</code>, await hooks return a <code>Promise</code> when executed.
393 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.
394 </p>
395
396 <?php
397 $lines = array(
398 '<script nonce="<?php print getNonce() ?>">',
399 ' document.addEventListener(\'Dolibarr:Ready\', async function(e) {',
400 '',
401 ' // Register async hooks will be executed in first place',
402 ' Dolibarr.onAwait(\'calculateDiscount\', async function(order) {',
403 ' order.total *= 0.9; // Apply 10% discount',
404 ' return order;',
405 ' }, { id: \'discount10\' });',
406 '',
407 ' // Register async hooks will be executed in third place',
408 ' Dolibarr.onAwait(\'calculateDiscount\', async function(order) {',
409 ' if(order.total > 1000) order.total -= 50; // Extra discount over 1000',
410 ' return order;',
411 ' }, { id: \'discountOver1000\', after: \'discount10\' });',
412 '',
413 ' // Register async hooks will be executed in second place',
414 ' // this hook item as no id so plus10HookItemId will receive a unique random id ',
415 ' let plus10HookItemId = Dolibarr.onAwait(\'calculateDiscount\', async function(order) {',
416 ' order.newObjectAttribute = \'My value\';',
417 ' order.total += 10;',
418 ' return order;',
419 ' }, { before: \'discountOver1000\' });',
420 '',
421 ' document.getElementById(\'try-event-yourCustomAwaitHookName\').addEventListener(\'click\', async function(e) {',
422 ' // Execute all registered await hooks sequentially',
423 ' let order = {total: 1200};',
424 ' order = await Dolibarr.executeHookAwait(\'calculateDiscount\', order);',
425 ' console.log(order); // order.total : 1200 -> 1080 -> 1090 -> 1040',
426 ' });',
427 '',
428 ' });',
429 '</script>',
430 );
431 $documentation->showCode($lines, 'php'); ?>
432
433 <div class="documentation-example">
434 Open your console <code>F12</code> and click on <button class="button" id="try-event-yourCustomAwaitHookName">try</button>
435
436 <script nonce="<?php print getNonce() ?>">
437 document.addEventListener('Dolibarr:Ready', async function(e) {
438
439 // Register async hooks will be executed in first place
440 Dolibarr.onAwait('calculateDiscount', async function(order) {
441 order.total *= 0.9; // Apply 10% discount
442 return order;
443 }, { id: 'discount10' });
444
445 // Register async hooks will be executed in third place
446 Dolibarr.onAwait('calculateDiscount', async function(order) {
447 if(order.total > 1000) order.total -= 50; // Extra discount over 1000
448 return order;
449 }, { id: 'discountOver1000', after: 'discount10' });
450
451 // Register async hooks will be executed in second place
452 Dolibarr.onAwait('calculateDiscount', async function(order) {
453 order.newObjectAttribute = 'My value';
454 order.total+= 10;
455 return order;
456 }, { before: 'discountOver1000' });
457
458 document.getElementById('try-event-yourCustomAwaitHookName').addEventListener('click', async function(e) {
459 // Execute all registered await hooks sequentially
460 let order = {total: 1200};
461 order = await Dolibarr.executeHookAwait('calculateDiscount', order);
462 console.log(order); // order.total : 1200 -> 1080 -> 1090 -> 1040
463 });
464
465 });
466 </script>
467 </div>
468
469 </div>
470
471 <div class="documentation-section">
472 <h2 id="titlesection-dom-initnewcontent" class="documentation-title">
473 initNewContent event system
474 </h2>
475
476 <p>
477 The <strong>initNewContent</strong> event is a standardized Dolibarr mechanism
478 to re-initialize UI components on dynamically added content.
479 Use it whenever you inject new DOM elements via AJAX, templates, or other dynamic updates.
480 </p>
481
482 <h3 id="titlesection-usecase-tooltips" class="documentation-title">
483 Use Case example: Dynamic Tooltips
484 </h3>
485
486 <p>
487 In a typical Dolibarr page, tooltips are initialized on page load for all elements
488 that have the class <code>.classfortooltip</code>. This works perfectly for static content.
489 </p>
490
491 <p>
492 However, when a section of the page is dynamically recreated or loaded via AJAX,
493 the new elements with <code>.classfortooltip</code> do not automatically have tooltips,
494 because the initialization script has already run on the initial DOM and is not rerun for the new elements.
495 </p>
496
497 <p>
498 The <strong>initNewContent</strong> mechanism solves this problem by providing a standardized hook
499 to re-initialize all interactive components on newly added DOM elements.
500 Developers can listen to <code>initNewContent</code> and re-run tooltip initialization
501 (or any other dynamic behavior) only on the new elements or their children, ensuring consistency and avoiding duplication.
502 </p>
503
504 <p>
505 This approach guarantees that tooltips, dialogs, and other interactive components
506 remain functional even when content is injected or updated asynchronously.
507 </p>
508
509 <p>
510 In addition to <code>document.ready</code> or <code>$(document).ready()</code>,
511 listen to <strong>initNewContent</strong> to ensure that tooltips, dialogs, or other interactive components
512 are properly initialized on any new DOM fragment added dynamically.
513 </p>
514
515
516 <div class="documentation-example">
517 <p>
518 <button class="button" id="try-no-initNewContent">Test without event</button>
519 <button class="button" id="try-initNewContent">Test with initNewContent event</button>
520 </p>
521 <div id="initNewContent-test-container"></div>
522
523 <style>
524 /* Animation for highlighting new content */
525 @keyframes highlightfortest {
526 from { background-color: #fffa8d; }
527 to { background-color: transparent; }
528 }
529 .highlightfortest {
530 padding: 10px;
531 animation: highlightfortest 1s ease-out;
532 }
533 </style>
534 <div id="idfortooltiponclick_doc-event-dialog-test" class="classfortooltiponclicktext" title="The title" style="display: none" >
535 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce nec elit venenatis, bibendum dui in, tristique dolor. In hac habitasse platea dictumst.
536 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.
537 Nulla sed felis et lacus tristique finibus. Cras ornare tincidunt. Aenean hendrerit volutpat efficitur. Integer vestibulum dui eget lectus pulvinar, vel mattis odio facilisis.
538 Etiam convallis scelerisque lobortis. Mauris tristique, quam dignissim sollicitudin sodales, elit ligula venenatis neque, sit amet interdum lacus tellus id tellus.
539 Mauris eu pretium turpis. Proin porta sem eget nisl vulputate vehicula.
540 </div>
541 <script nonce="<?php print getNonce() ?>">
542 document.addEventListener('Dolibarr:Ready', function(e) {
543 const container = document.getElementById('initNewContent-test-container');
544
545 document.getElementById('try-no-initNewContent').addEventListener('click', function() {
546 container.innerHTML = `<span class="classfortooltip highlightfortest" title="this is the title">A text with a tooltip but the tooltip isn't load</span>
547 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>`;
548 });
549
550 document.getElementById('try-initNewContent').addEventListener('click', function() {
551 container.innerHTML = `<span class="classfortooltip highlightfortest" title="this is the title">A text with a tooltip and the tooltip is loaded</span>
552 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>`;
553 Dolibarr.initNewContent(container);
554 });
555 });
556 </script>
557
558
559 </div>
560 <?php
561 $lines = array(
562 '<div id="idfortooltiponclick_doc-event-dialog-test" class="classfortooltiponclicktext" title="The title" >Lorem ipsum .....</div>',
563 '<script nonce="<?php print getNonce() ?>">',
564 'document.addEventListener("Dolibarr:Ready", function(e) {',
565 ' const container = document.getElementById("initNewContent-test-container");',
566 '',
567 ' // Insert content without calling initNewContent',
568 ' document.getElementById("try-no-initNewContent").addEventListener("click", function() {',
569 ' container.innerHTML = `<span class="classfortooltip highlightfortest" title="this is the title">A text with a tooltip but the tooltip isn\'t load</span>',
570 ' 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>`;',
571 ' });',
572 '',
573 ' // Insert content and trigger initNewContent',
574 ' document.getElementById("try-initNewContent").addEventListener("click", function() {',
575 ' container.innerHTML = `<span class="classfortooltip highlightfortest" title="this is the title">A text with a tooltip and the tooltip is loaded</span>',
576 ' 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>`;',
577 ' Dolibarr.initNewContent(container);',
578 ' });',
579 '});',
580 '</script>',
581 );
582 $documentation->showCode($lines, 'php'); ?>
583
584 <h3 id="titlesection-usecase-tooltips" class="documentation-title">
585 How to use it
586 </h3>
587
588 <p>
589 The event handler receives an object with the property <code>targets</code>,
590 which is an array of DOM elements or jQuery collections to initialize. Each element can be:
591 </p>
592
593 <ul>
594 <li>a container with child elements to initialize</li>
595 <li>or a direct element that needs initialization</li>
596 </ul>
597
598 <h4>Example: Trigger initNewContent manually on a container</h4>
599
600 <?php
601 $lines = array(
602 '<script nonce="<?php print getNonce() ?>">',
603 ' document.addEventListener(\'Dolibarr:Ready\', function(e) {',
604 ' /* [... code that dynamically reloads part of the DOM ...] */',
605 '',
606 ' /**',
607 ' * true: only include the children of each target element',
608 ' * false: include the target elements themselves',
609 ' */',
610 ' const applyToChildrenOnly = true;',
611 '',
612 ' // Trigger initNewContent manually on a jQuery container',
613 ' Dolibarr.initNewContent($("#myContainer"), applyToChildrenOnly);',
614 '',
615 ' // Trigger initNewContent manually on a vanilla JS element',
616 ' const element = document.getElementById("myContainer");',
617 ' Dolibarr.initNewContent(element, applyToChildrenOnly);',
618 ' });',
619 '</script>',
620 );
621 $documentation->showCode($lines, 'php'); ?>
622
623 <p>
624 Dolibarr provides a custom event system to properly initialize dynamic content.
625 Always use <strong>initNewContent</strong> when working with AJAX-injected fragments or
626 dynamically created elements instead of relying solely on jQuery document ready.
627 </p>
628
629
630
631 <h4>Example in pure JS style: listening to initNewContent</h4>
632 <?php
633 $lines = array(
634 '<script nonce="<?php print getNonce() ?>">',
635 ' Dolibarr.on("initNewContent", ({ targets }) => {',
636 ' targets.forEach(root => {',
637 '',
638 ' // Array to store all matching dialog elements',
639 ' const dialogs = [];',
640 '',
641 ' // Include the root element if it matches the selector',
642 ' if (root.matches(".classfortooltiponclicktext")) {',
643 ' dialogs.push(root);',
644 ' }',
645 '',
646 ' // Add all descendants matching the selector',
647 ' dialogs.push(...root.querySelectorAll(".classfortooltiponclicktext"));',
648 '',
649 ' // Initialize each dialog element',
650 ' dialogs.forEach(el => {',
651 ' // Your code to initialize the tooltip/dialog or other stuff',
652 ' });',
653 ' });',
654 ' });',
655 '</script>',
656 );
657 $documentation->showCode($lines, 'php');
658 ?>
659
660 <h4>Compact version in pure JS</h4>
661 <?php
662 $lines = array(
663 '<script nonce="<?php print getNonce() ?>">',
664 ' Dolibarr.on("initNewContent", ({ targets }) => {',
665 ' targets.forEach(root => {',
666 ' const dialogs = [',
667 ' ...(root.matches(".classfortooltiponclicktext") ? [root] : []),',
668 ' ...root.querySelectorAll(".classfortooltiponclicktext")',
669 ' ];',
670 ' dialogs.forEach(el => {',
671 ' // Initialize tooltip/dialog or other stuff here',
672 ' });',
673 ' });',
674 ' });',
675 '</script>',
676 );
677 $documentation->showCode($lines, 'php');
678 ?>
679
680 <h4>Example in jQuery style</h4>
681 <?php
682 $lines = array(
683 '<script nonce="<?php print getNonce() ?>">',
684 ' Dolibarr.on("initNewContent", ({ targets }) => {',
685 ' targets.forEach($root => {',
686 ' const $dialogs = $root',
687 ' .filter(".classfortooltiponclicktext")',
688 ' .add($root.find(".classfortooltiponclicktext"));',
689 ' $dialogs.each(function () {',
690 ' const $el = $(this);',
691 ' // Initialize tooltip/dialog behavior or other stuff here',
692 ' });',
693 ' });',
694 ' });',
695 '</script>',
696 );
697 $documentation->showCode($lines, 'php');
698 ?>
699
700 </div>
701
702
703
704 <div class="documentation-section">
705 <h2 id="titlesection-create-tool-example" class="documentation-title">Example of creating a new context tool</h2>
706
707 <h3>Defining Tools</h3>
708 <p>
709 You can define reusable and protected tools in the Dolibarr context using <code>Dolibarr.defineTool</code>.
710 </p>
711 <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>
712 <p><b>Note :</b> a tool can be a class not only a function</p>
713
714 <?php
715 $lines = array(
716 '<script>',
717 'document.addEventListener(\'Dolibarr:Init\', function(e) {',
718 ' // Define a simple protected tool : once defined, it cannot be replaced.',
719 ' Dolibarr.defineTool(\'alertUser\', (msg) => alert(\'[Dolibarr] \' + msg));',
720 '',
721 ' // Define an overwritable tool : it can be replaced later by another call with overwrite: true',
722 ' Dolibarr.defineTool(\'notifyUser\', (msg) => console.log(msg), { overwrite: true });',
723 '});',
724 '',
725 'document.addEventListener(\'Dolibarr:Ready\', function(e) {',
726 ' // Use the tool',
727 ' Dolibarr.tools.alertUser(\'hello world\');',
728 '});',
729 '</script>',
730 );
731 $documentation->showCode($lines, 'php'); ?>
732
733 <h3>Protected Tools</h3>
734 <p>
735 A tool defined without <code>overwrite</code> is protected: it can never be replaced, even with <code>{ overwrite: true }</code>.
736 A tool defined with <code>{ overwrite: true }</code> can be replaced, but only by another call using <code>{ overwrite: true }</code>.
737 Any other attempt throws an error:
738 </p>
739
740 <?php
741 $lines = array(
742 '<script>',
743 ' try {',
744 ' Dolibarr.defineTool(\'alertUser\', () => {}, { overwrite: true }); // alertUser is protected',
745 ' } catch (e) {',
746 ' console.error(e.message);',
747 ' }',
748 '</script>',
749 );
750 $documentation->showCode($lines, 'php'); ?>
751
752 <h3>Reading Tools</h3>
753 <p>
754 You can read the list of available tools using <code>Dolibarr.tools</code>. It returns a frozen copy:
755 </p>
756
757 <?php
758 $lines = array(
759 '<script>',
760 ' console.log(Dolibarr.tools);',
761 ' if(Dolibarr.checkToolExist(\'Tool name to check\')){/* ... */}else{/* ... */}; ',
762 '</script>',
763 );
764 $documentation->showCode($lines, 'php'); ?>
765
766 </div>
767
768 <div class="documentation-section">
769 <h2 id="titlesection-compat" class="documentation-title">Backward compatibility and deprecations</h2>
770 <p>
771 When the behavior of the context changes, old usages keep working thanks to a backward compatibility layer
772 (<code>dolibarr-context.compat.js</code>, loaded right after the context definition).
773 Each old usage shows a warning in the browser console, once per page.
774 </p>
775 <ul>
776 <li>The backward compatibility layer is enabled in Dolibarr 25.0 and 26.0, and will be removed in Dolibarr 27.0.</li>
777 <li>Set the hidden constant <code>MAIN_JS_CONTEXT_DISABLE_COMPAT</code> to 1 to test your modules without it.</li>
778 <li>List the deprecated usages of the current page with <code>Dolibarr.getDeprecations()</code>.</li>
779 <li>Tools can report their own deprecated usages with <code>Dolibarr.deprecated(key, message)</code>.</li>
780 </ul>
781 <p>Deprecated usages:</p>
782 <ul>
783 <li><code>Dolibarr.defineTool(name, value, overwrite, triggerHook)</code>: use <code>Dolibarr.defineTool(name, value, { overwrite, triggerHook })</code>.</li>
784 </ul>
785 <?php
786 $lines = array(
787 '<script>',
788 ' // Report a deprecated usage in your own tool',
789 ' Dolibarr.deprecated(\'myTool.oldMethod\', \'myTool.oldMethod() is deprecated, use myTool.newMethod() instead\');',
790 '',
791 ' // List deprecated usages reported on this page',
792 ' console.table(Dolibarr.getDeprecations());',
793 '</script>',
794 );
795 $documentation->showCode($lines, 'php'); ?>
796 </div>
797
798 <?php include __DIR__ . '/inc_seteventmessage.php'; ?>
799
800 <?php include __DIR__ . '/inc_fetch.php'; ?>
801
802
803 <div class="documentation-section">
804 <h2 id="titlesection-contextvars" class="documentation-title">Set and use context vars</h2>
805
806 <p>
807 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.
808 By using context vars, you can:
809 <ul>
810 <li>Pass server-side data (from PHP) to JavaScript safely and consistently.</li>
811 <li>Provide reusable configuration for Dolibarr tools, widgets, or modules without hardcoding values.</li>
812 <li>Define overridable or non-overridable vars to protect critical values while allowing flexible overrides when necessary.</li>
813 <li>Use <code>Dolibarr.setContextVar</code> for single values or <code>Dolibarr.setContextVars</code> to pass multiple values at once.</li>
814 <li>Access these variables anywhere in your code via <code>Dolibarr.getContextVar(key)</code>.</li>
815 <li>Ensure that all your modules and tools can rely on consistent and up-to-date context information, improving maintainability and interoperability.</li>
816 </ul>
817 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.
818 </p>
819
820 <h3>Add context var (overridable or not)</h3>
821 <p>
822 A context var set without <code>overwrite</code> is protected: it can never be replaced.
823 A context var set with <code>overwrite</code> to <code>true</code> can be replaced, but only by another call with <code>overwrite</code> to <code>true</code>.
824 Any other attempt throws an error.
825 </p>
826 <?php
827 $lines = array(
828 '<script nonce="<?php print getNonce() ?>" >',
829 ' document.addEventListener(\'Dolibarr:Init\', function(e) {',
830 ' // Add no overridable context var',
831 ' Dolibarr.setContextVar(\'yourKey\', \'YourValue\');',
832 '',
833 ' // Add overridable context var',
834 ' Dolibarr.setContextVar(\'yourKey2\', \'YourValue\', true);',
835 '',
836 ' // Replace the overridable context var',
837 ' Dolibarr.setContextVar(\'yourKey2\', \'YourNewValue\', true);',
838 ' });',
839 '</script>',
840 );
841 $documentation->showCode($lines, 'php');
842 ?>
843
844
845 <h3>Add multiple context vars (overridable or not)</h3>
846 <?php
847 $lines = array(
848 '<?php',
849 ' $contextConst = [',
850 ' \'DOL_URL_ROOT\' => DOL_URL_ROOT,',
851 ' \'token\' => newToken(),',
852 ' \'cardObjectElement\' => $object->element,',
853 ' \'cardObjectId\' => $object->id,',
854 ' \'currentUserId\' => $user->id',
855 ' // ...',
856 ' ];',
857 '',
858 ' $contextVars = [',
859 ' \'lastCardDataRefresh\' => time(),',
860 ' // ...',
861 ' ]',
862 '?>',
863 '<script nonce="<?php print getNonce() ?>" >',
864 ' document.addEventListener(\'Dolibarr:Init\', function(e) {',
865 ' Dolibarr.setContextVars(<?php print json_encode($contextConst); ?>);',
866 ' Dolibarr.setContextVars(<?php print json_encode($contextVars); ?>, true);',
867 ' });',
868 '</script>',
869 );
870 $documentation->showCode($lines, 'php');
871 ?>
872
873 <h3 id="titlesection-contextvars-module">Add context vars from a module (PHP hook)</h3>
874 <p>
875 A module can add context vars from PHP with the hook <code>addJsContextVars</code> (context <code>main</code>).
876 They are set with the core context vars, before <code>Dolibarr:Init</code>, so they are available to all tools and scripts.
877 </p>
878 <ul>
879 <li>Return the vars into <code>$this->results</code>, as an array key =&gt; value.</li>
880 <li>Values must be a string, a number or a boolean, other values are ignored.</li>
881 <li>A var already defined by Dolibarr (ex: <code>DOL_URL_ROOT</code>) or by another module is ignored. Prefix your keys with your module name.</li>
882 <li>These vars are protected: they can't be replaced in JS.</li>
883 <li><code>$parameters['jsContextVars']</code> contains the core context vars (read only).</li>
884 </ul>
885 <?php
886 $lines = array(
887 '<?php',
888 '// In the hook class of your module (class/actions_mymodule.class.php), with \'main\' in the hook contexts of the module descriptor',
889 'public function addJsContextVars($parameters, &$object, &$action, $hookmanager)',
890 '{',
891 ' global $user;',
892 '',
893 ' $this->results = array(',
894 ' \'MYMODULE_INTERFACE_URL\' => dol_buildpath(\'/mymodule/ajax/interface.php\', 1),',
895 ' \'MYMODULE_CAN_WRITE\' => (bool) $user->hasRight(\'mymodule\', \'myobject\', \'write\'),',
896 ' );',
897 '',
898 ' return 0;',
899 '}',
900 );
901 $documentation->showCode($lines, 'php');
902 ?>
903
904 <h3>Get context var</h3>
905 <?php
906 $lines = array(
907 '<script nonce="<?php print getNonce() ?>" >',
908 ' document.addEventListener(\'Dolibarr:Ready\', function(e) {',
909 ' let url = Dolibarr.getContextVar(\'DOL_URL_ROOT\', \'The optional fallback value\'));',
910 ' console.log(url);',
911 ' });',
912 '</script>',
913 );
914 $documentation->showCode($lines, 'php');
915 ?>
916
917 </div>
918
919 </div>
920
921
922
923
924</div>
925
926</div>
927<?php
928// Output close body + html
929$documentation->docFooter();
930?>
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
Class Context.
Class to manage UI documentation.
$conf browser version
Definition main.inc.php:229
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
Definition receipt.php:492
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:166
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
a disabled
editval_textarea active