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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## Unreleased

### Fixed

- Fix visibility conditions on tree cascade dropdown questions

## [1.1.1] - 2026-05-27

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion public/js/modules/AfTreeCascadeDropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export class AfTreeCascadeDropdown {
const value = $select.val();
const fieldName = $select.data('af-tree-field-name');
if (fieldName) {
$(`input[name="${fieldName}"]`).val(value);
$(`input[name="${fieldName}"]`).val(value).trigger('input');
}

const $wrapper = $select.closest('.af-tree-level-wrapper');
Expand Down
118 changes: 118 additions & 0 deletions src/Model/ConditionHandler/TreeCascadeItemAsTextConditionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?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\Model\ConditionHandler;

use CommonDBTM;
use CommonTreeDropdown;
use Glpi\Form\Condition\ConditionData;
use Glpi\Form\Condition\ConditionHandler\ConditionHandlerInterface;
use Glpi\Form\Condition\ValueOperator;
use Override;

/**
* Like ItemAsTextConditionHandler but uses completename for CommonTreeDropdown
* items so that conditions on parent nodes work correctly.
*
* Core's ItemAsTextConditionHandler uses getName() which returns only the
* item's own name. For tree dropdowns, a child's own name does not include
* its ancestors, so "contains <parent name>" always fails. Using completename
* (e.g. "Parent > Child") makes the full path available for matching.
*/
final readonly class TreeCascadeItemAsTextConditionHandler implements ConditionHandlerInterface
{
public function __construct(
private string $itemtype,
) {}

#[Override]
public function getSupportedValueOperators(): array
{
return [
ValueOperator::CONTAINS,
ValueOperator::NOT_CONTAINS,
];
}

#[Override]
public function getTemplate(): string
{
return '/pages/admin/form/condition_handler_templates/input.html.twig';
}

/**
* @return array<string, mixed>
*/
#[Override]
public function getTemplateParameters(ConditionData $condition): array
{
return [];
}

#[Override]
public function applyValueOperator(
mixed $a,
ValueOperator $operator,
mixed $b,
): bool {
if (!is_array($a) || !isset($a['items_id'])) {
return false;
}

$item = $this->itemtype::getById($a['items_id']);
if (!$item) {
return false;
}

// Use completename for tree dropdowns so that conditions referencing
// ancestor nodes match correctly (e.g. "contains Parent" matches a child
// whose completename is "Parent > Child").
/** @var CommonDBTM $item */
if ($item instanceof CommonTreeDropdown) {
$completename = $item->fields['completename'];
$text = is_string($completename) ? $completename : '';
} else {
$text = $item->getName();
}

$a = strtolower($text);

$b = is_scalar($b) || $b === null ? strtolower((string) $b) : '';

return match ($operator) {
ValueOperator::CONTAINS => str_contains($a, $b),
ValueOperator::NOT_CONTAINS => !str_contains($a, $b),
default => false,
};
}
}
28 changes: 28 additions & 0 deletions src/Model/QuestionType/TreeCascadeDropdownQuestion.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,16 @@
use DBmysql;
use CommonTreeDropdown;
use Glpi\Application\View\TemplateRenderer;
use Glpi\DBAL\JsonFieldInterface;
use Glpi\Form\Condition\ConditionHandler\ItemAsTextConditionHandler;
use Glpi\Form\Question;
use Glpi\Form\QuestionType\QuestionTypeCategoryInterface;
use Glpi\Form\QuestionType\QuestionTypeItemDropdown;
use Glpi\Form\QuestionType\QuestionTypeItemExtraDataConfig;
use GlpiPlugin\Advancedforms\Model\ConditionHandler\TreeCascadeItemAsTextConditionHandler;
use GlpiPlugin\Advancedforms\Model\Config\ConfigurableItemInterface;
use GlpiPlugin\Advancedforms\Model\QuestionType\AdvancedCategory;
use InvalidArgumentException;
use Override;

final class TreeCascadeDropdownQuestion extends QuestionTypeItemDropdown implements ConfigurableItemInterface
Expand Down Expand Up @@ -404,6 +409,29 @@ private function getValidItemsForLevel(string $table, array $base_where, array $
return $items;
}

#[Override]
public function getConditionHandlers(?JsonFieldInterface $question_config): array
{
if (!$question_config instanceof QuestionTypeItemExtraDataConfig) {
throw new InvalidArgumentException();
}

$handlers = parent::getConditionHandlers($question_config);

// Replace ItemAsTextConditionHandler with the tree-aware variant that
// uses completename so conditions on ancestor nodes match correctly.
$handlers = array_filter(
$handlers,
fn($handler) => !($handler instanceof ItemAsTextConditionHandler),
);

if ($question_config->getItemtype()) {
$handlers[] = new TreeCascadeItemAsTextConditionHandler($question_config->getItemtype());
}

return array_values($handlers);
}

#[Override]
public function prepareEndUserAnswer(Question $question, mixed $answer): mixed
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
<?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\Tests\Model\ConditionHandler;

use Glpi\Form\Condition\Engine;
use Glpi\Form\Condition\EngineInput;
use Glpi\Form\Condition\LogicOperator;
use Glpi\Form\Condition\Type;
use Glpi\Form\Condition\ValueOperator;
use Glpi\Form\Condition\VisibilityStrategy;
use Glpi\Form\QuestionType\QuestionTypeItemDropdownExtraDataConfig;
use Glpi\Form\QuestionType\QuestionTypeShortText;
use Glpi\Tests\FormBuilder;
use GlpiPlugin\Advancedforms\Model\QuestionType\TreeCascadeDropdownQuestion;
use GlpiPlugin\Advancedforms\Tests\AdvancedFormsTestCase;
use Location;
use Session;

/**
* Tests that the CONTAINS/NOT_CONTAINS condition operators on a TreeCascadeDropdown
* question match against the item's full completename (hierarchical path) rather
* than just its own name.
*
* Regression: selecting a child item only matched conditions against its own
* name, so conditions referencing an ancestor were always false.
*/
final class TreeCascadeItemAsTextConditionHandlerTest extends AdvancedFormsTestCase
{
/**
* Verify that CONTAINS evaluates to true when the searched text appears in
* the completename of the selected item but not in its own name alone.
*/
public function testContainsMatchesCompletename(): void
{
$this->login();
$this->enableConfigurableItem(TreeCascadeDropdownQuestion::class);

$entity_id = Session::getActiveEntity();

$parent = $this->createItem(Location::class, [
'name' => 'Parent Location',
'locations_id' => 0,
'entities_id' => $entity_id,
]);

$child = $this->createItem(Location::class, [
'name' => 'Child Location',
'locations_id' => $parent->getID(),
'entities_id' => $entity_id,
]);

$extra_data = json_encode(new QuestionTypeItemDropdownExtraDataConfig(
itemtype: Location::class,
));

$form_builder = new FormBuilder("Test form");
$form_builder->addQuestion(
name: "My location",
type: TreeCascadeDropdownQuestion::class,
extra_data: $extra_data,
);
$form_builder->addQuestion("Dependent question", QuestionTypeShortText::class);
$form_builder->setQuestionVisibility("Dependent question", VisibilityStrategy::VISIBLE_IF, [
[
'logic_operator' => LogicOperator::AND,
'item_name' => "My location",
'item_type' => Type::QUESTION,
'value_operator' => ValueOperator::CONTAINS,
'value' => 'Parent Location',
],
]);

$form = $this->createForm($form_builder);

$answers = [
$this->getQuestionId($form, "My location") => [
'itemtype' => Location::class,
'items_id' => $child->getID(),
],
];

$engine = new Engine($form, new EngineInput($answers));
$output = $engine->computeVisibility();

$dependent_id = $this->getQuestionId($form, "Dependent question");
$this->assertTrue(
$output->isQuestionVisible($dependent_id),
"Condition 'contains Parent Location' should match a child item "
. "whose completename is 'Parent Location > Child Location'",
);
}

/**
* Verify that NOT_CONTAINS evaluates to false when the searched text appears
* in the completename of the selected item (via an ancestor).
*/
public function testNotContainsMatchesCompletename(): void
{
$this->login();
$this->enableConfigurableItem(TreeCascadeDropdownQuestion::class);

$entity_id = Session::getActiveEntity();

$parent = $this->createItem(Location::class, [
'name' => 'Parent Location',
'locations_id' => 0,
'entities_id' => $entity_id,
]);

$child = $this->createItem(Location::class, [
'name' => 'Child Location',
'locations_id' => $parent->getID(),
'entities_id' => $entity_id,
]);

$extra_data = json_encode(new QuestionTypeItemDropdownExtraDataConfig(
itemtype: Location::class,
));

$form_builder = new FormBuilder("Test form not contains");
$form_builder->addQuestion(
name: "My location",
type: TreeCascadeDropdownQuestion::class,
extra_data: $extra_data,
);
$form_builder->addQuestion("Dependent question", QuestionTypeShortText::class);
$form_builder->setQuestionVisibility("Dependent question", VisibilityStrategy::VISIBLE_IF, [
[
'logic_operator' => LogicOperator::AND,
'item_name' => "My location",
'item_type' => Type::QUESTION,
'value_operator' => ValueOperator::NOT_CONTAINS,
'value' => 'Parent Location',
],
]);

$form = $this->createForm($form_builder);

$answers = [
$this->getQuestionId($form, "My location") => [
'itemtype' => Location::class,
'items_id' => $child->getID(),
],
];

$engine = new Engine($form, new EngineInput($answers));
$output = $engine->computeVisibility();

$dependent_id = $this->getQuestionId($form, "Dependent question");
$this->assertFalse(
$output->isQuestionVisible($dependent_id),
"Condition 'not contains Parent Location' should NOT match a child item "
. "whose completename is 'Parent Location > Child Location'",
);
}
}