Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions public/js/modules/AfTreeCascadeDropdown.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* -------------------------------------------------------------------------
* advancedforms plugin for GLPI
* -------------------------------------------------------------------------
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* -------------------------------------------------------------------------
* @copyright Copyright (C) 2025 by the advancedforms plugin team.
* @license MIT https://opensource.org/licenses/mit-license.php
* @link https://github.com/pluginsGLPI/advancedforms
* -------------------------------------------------------------------------
*/

export class AfTreeCascadeDropdown {
/**
* @param {Object} options
* @param {string} options.selector_id - The ID of the select element to bind
* @param {number} options.questions_id - The ID of the question
* @param {number} options.ajax_limit_count - Limit for Select2 adaptation
* @param {string} [options.next_container_id] - Optional container ID for auto-loading children
* @param {number} [options.auto_load_parent_id] - Optional parent ID to auto-load children on init
* @param {number} [options.level] - Current depth level (1 = root)
*/
constructor(options) {
this.selector_id = options.selector_id;
this.questions_id = options.questions_id;
this.ajax_limit_count = options.ajax_limit_count || 10;
this.next_container_id = options.next_container_id || null;
this.auto_load_parent_id = options.auto_load_parent_id || 0;
this.level = options.level || 1;
this.endpoint_url = `${CFG_GLPI.root_doc}/plugins/advancedforms/TreeDropdownChildren`;

this.#init();
}

#init() {
const $select = $(`#${this.selector_id}`);
if ($select.length === 0) {
return;
}

this.#setupAdapt($select);
this.#bindChangeEvent($select);

if (this.auto_load_parent_id > 0 && this.next_container_id) {
this.#loadChildren(this.auto_load_parent_id, $(`#${this.next_container_id}`));
}
}

#setupAdapt($select) {
if ($select.hasClass('af-tree-cascade-select')) {
setupAdaptDropdown({
field_id: this.selector_id,
width: '100%',
dropdown_css_class: '',
placeholder: '',
ajax_limit_count: this.ajax_limit_count,
templateresult: templateResult,
templateselection: templateSelection,
});
}
}

#bindChangeEvent($select) {
$select.on('change', () => {
const value = $select.val();
const fieldName = $select.data('af-tree-field-name');
if (fieldName) {
$(`input[name="${fieldName}"]`).val(value);
}

const $wrapper = $select.closest('.af-tree-level-wrapper');
$wrapper.nextAll('.af-tree-level-wrapper, .af-tree-next-container').remove();

if (value && value > 0) {
const $parentRow = $wrapper.parent();
const $container = $(`<div class="af-tree-next-container"></div>`);
$parentRow.append($container);
this.#loadChildren(value, $container);
}
});
}

#loadChildren(parent_id, $container) {
$.ajax({
url: this.endpoint_url,
data: {
questions_id: this.questions_id,
parent_id: parent_id,
},
success: (html) => {
if (html.trim().length > 0) {
$container.html(html);
this.#initDynamicChild($container);
} else {
$container.remove();
}
},
});
}

#initDynamicChild($container) {
const $select = $container.find('.af-tree-cascade-select');
if ($select.length === 0) {
return;
}

const child_id = $select.attr('id');
const child_options = {
selector_id: child_id,
questions_id: $select.data('af-tree-questions-id') || this.questions_id,
ajax_limit_count: $select.data('af-tree-ajax-limit') || this.ajax_limit_count,
level: this.level + 1,
};

new AfTreeCascadeDropdown(child_options);
}
};
3 changes: 3 additions & 0 deletions setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
* -------------------------------------------------------------------------
*/

use Glpi\Application\ImportMapGenerator;
use Glpi\Plugin\HookManager;
use GlpiPlugin\Advancedforms\Service\InitManager;

Expand Down Expand Up @@ -61,6 +62,8 @@ function plugin_init_advancedforms(): void
$hook_manager->registerCSSFile('css/advancedforms.css');
$hook_manager->registerJavascriptFile('js/advancedforms.js');

ImportMapGenerator::getInstance()->registerModulesPath('advancedforms', '/public/js/modules');

InitManager::getInstance()->init();
}

Expand Down
154 changes: 154 additions & 0 deletions src/Controller/TreeDropdownChildrenController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
<?php

/**
* -------------------------------------------------------------------------
* advancedforms plugin for GLPI
* -------------------------------------------------------------------------
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* -------------------------------------------------------------------------
* @copyright Copyright (C) 2025 by the advancedforms plugin team.
* @license MIT https://opensource.org/licenses/mit-license.php
* @link https://github.com/pluginsGLPI/advancedforms
* -------------------------------------------------------------------------
*/

namespace GlpiPlugin\Advancedforms\Controller;

use Glpi\Form\Question;
use Glpi\Form\QuestionType\QuestionTypeItemDropdown;
use DBmysql;
use CommonTreeDropdown;
use Glpi\Application\View\TemplateRenderer;
use Glpi\Controller\AbstractController;
use Glpi\Http\Firewall;
use Glpi\Security\Attribute\SecurityStrategy;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class TreeDropdownChildrenController extends AbstractController
{
#[SecurityStrategy(Firewall::STRATEGY_AUTHENTICATED)]
#[Route(
path: 'TreeDropdownChildren',
name: 'tree_dropdown_children',
)]
public function __invoke(Request $request): Response
{
$questions_id = $request->query->getInt('questions_id', 0);
$parent_id = $request->query->getInt('parent_id', 0);

if ($parent_id <= 0 || $questions_id <= 0) {
return new Response('', Response::HTTP_OK);
}

$question = new Question();
if (!$question->getFromDB($questions_id)) {
return new Response('', Response::HTTP_OK);
}

/** @var QuestionTypeItemDropdown $question_type */
$question_type = $question->getQuestionType();

$itemtype = $question_type->getDefaultValueItemtype($question) ?? '';
$field_name = $question->getEndUserInputName() . '[items_id]';
$aria_label = $question_type->items_id_aria_label ?? __('Select a dropdown item');

$dropdown_restriction_params = $question_type->getDropdownRestrictionParams($question);
/** @var array<string, mixed> $condition_param */
$condition_param = $dropdown_restriction_params['WHERE'] ?? [];

if (!class_exists($itemtype) || !is_subclass_of($itemtype, CommonTreeDropdown::class)) {
return new Response('', Response::HTTP_OK);
}

/** @var DBmysql $DB */
global $DB;

$foreign_key = $itemtype::getForeignKeyField();
$table = $itemtype::getTable();

$level_key = $table . '.level';

$where = [];

$entity_restrict = getEntitiesRestrictCriteria($table);
if (!empty($entity_restrict)) {
$where = array_merge($where, $entity_restrict);
}

if (!empty($condition_param) && is_array($condition_param)) {
unset($condition_param[$level_key]);
$where = array_merge($where, $condition_param);
}

$where[$foreign_key] = $parent_id;

$item_check = getItemForItemtype($itemtype);
if ($item_check instanceof CommonTreeDropdown && $item_check->isField('is_deleted')) {
$where['is_deleted'] = 0;
}

$children = [];
$iterator = $DB->request([
'SELECT' => ['id', 'name'],
'FROM' => $table,
'WHERE' => $where,
'ORDER' => 'name ASC',
]);

foreach ($iterator as $row) {
if (!is_array($row)) {
continue;
}

$children[] = [
'id' => $row['id'],
'name' => $row['name'],
];
}

if ($children === []) {
return new Response('', Response::HTTP_OK);
}

global $CFG_GLPI;

$rand_value = random_int(1000000, 9999999);
$select_id = 'tree_cascade_child_' . $rand_value;

$twig = TemplateRenderer::getInstance();
$html = $twig->render(
'@advancedforms/tree_cascade_dropdown_children.html.twig',
[
'select_id' => $select_id,
'children' => $children,
'questions_id' => $questions_id,
'final_field_name' => $field_name,
'aria_label' => $aria_label,
'ajax_limit_count' => is_numeric($CFG_GLPI['ajax_limit_count'] ?? 10) ? (int) ($CFG_GLPI['ajax_limit_count'] ?? 10) : 10,
],
);

return new Response($html, Response::HTTP_OK, ['Content-Type' => 'text/html; charset=UTF-8']);
Comment on lines +140 to +152
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use $this->render() directly, which will handle the response creation for you.

Copy link
Author

@Lainow Lainow Mar 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without the return new Response() statement, it doesn't seem to work.

image

}
}
Loading