Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Field option profile restrictions #18873

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion ajax/asset/assetdefinition.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@
use Glpi\Exception\Http\NotFoundHttpException;

Session::checkRight(AssetDefinition::$rightname, READ);
Session::writeClose();

if ($_REQUEST['action'] === 'get_all_fields') {
Session::writeClose();
header("Content-Type: application/json; charset=UTF-8");
$definition = new AssetDefinition();
if (!$definition->getFromDB($_GET['assetdefinitions_id'])) {
Expand Down
13 changes: 11 additions & 2 deletions js/src/vue/CustomObject/FieldPreview/FieldDisplay.vue
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,17 @@
sortable_field.field_options = {};
form_data.entries().forEach(([name, value]) => {
if (name.startsWith('field_options[')) {
const option_name = name.replace('field_options[', '').slice(0, -1);
sortable_field.field_options[option_name] = value;
const is_array = name.endsWith('[]');
const option_name = name.replace('field_options[', '').replace(/\[\]/, '');
if (is_array) {
sortable_field.field_options[option_name] = sortable_field.field_options[option_name] ?? [];
if (!Array.isArray(sortable_field.field_options[option_name])) {
sortable_field.field_options[option_name] = [sortable_field.field_options[option_name]];
}
sortable_field.field_options[option_name].push(value);
} else {
sortable_field.field_options[option_name] = value;
}
}
});
} else if (btn_submit.attr('name') === 'purge') {
Expand Down
16 changes: 14 additions & 2 deletions src/Glpi/Asset/Asset.php
Original file line number Diff line number Diff line change
Expand Up @@ -337,17 +337,29 @@ public function showForm($ID, array $options = [])
$fields_display = static::getDefinition()->getDecodedFieldsField();
$core_field_options = [];

// Remove fields that are hidden for the current profile
$custom_fields = array_filter($custom_fields, static fn ($f) => !$f->getFieldType()->getOptionValues()['hidden']);

$core_fields = static::getDefinition()->getAllFields();
foreach ($fields_display as $field) {
$core_field_options[$field['key']] = $field['field_options'] ?? [];
$f = new CustomFieldDefinition();
$core_field = $core_fields[$field['key']];
$f->fields['system_name'] = $field['key'];
$f->fields['type'] = $core_field['type'];
$f->fields['field_options'] = $field['field_options'] ?? [];
$core_field_options[$field['key']] = $f->getFieldType()->getOptionValues();
}

$field_order = $this->getFormFields();
$field_order = array_filter($field_order, static fn ($f) => $core_field_options[$f]['hidden'] !== true);

TemplateRenderer::getInstance()->display(
'pages/assets/asset.html.twig',
[
'item' => $this,
'params' => $options,
'custom_fields' => $custom_fields,
'field_order' => $this->getFormFields(),
'field_order' => $field_order,
'additional_field_options' => $core_field_options,
]
);
Expand Down
2 changes: 1 addition & 1 deletion src/Glpi/Asset/AssetDefinition.php
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ public function showFieldOptionsForCoreField(string $field_key, array $field_opt
$custom_field->fields['itemtype'] = \Computer::class; // Doesn't matter what it is as long as it's not empty
$custom_field->fields['field_options'] = $field_options;

$options_allowlist = ['required', 'readonly', 'full_width'];
$options_allowlist = ['required', 'readonly', 'full_width', 'hidden'];

$twig_params = [
'options' => array_filter($custom_field->getFieldType()->getOptions(), static fn ($option) => in_array($option->getKey(), $options_allowlist, true)),
Expand Down
102 changes: 102 additions & 0 deletions src/Glpi/Asset/CustomFieldOption/ProfileRestrictOption.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php

/**
* ---------------------------------------------------------------------
*
* GLPI - Gestionnaire Libre de Parc Informatique
*
* http://glpi-project.org
*
* @copyright 2015-2025 Teclib' and contributors.
* @licence https://www.gnu.org/licenses/gpl-3.0.html
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* ---------------------------------------------------------------------
*/

namespace Glpi\Asset\CustomFieldOption;

use Glpi\Application\View\TemplateRenderer;

class ProfileRestrictOption extends AbstractOption
{
public function getFormInput(): string
{
$value = parent::getValue();
if (!is_array($value)) {
$value = [$value];
}
$twig_params = [
'item' => $this->custom_field,
'key' => $this->getKey(),
'label' => $this->getName(),
'value' => $value,
'inverted' => $this->getInverted(),
];
// language=Twig
return TemplateRenderer::getInstance()->renderFromStringTemplate(<<<TWIG
{% import 'components/form/fields_macros.html.twig' as fields %}
{% set match_invert_field %}
{{ fields.sliderField('field_options[' ~ key ~ '_invert]', inverted, __('Restrict to all but these profiles'), {
field_class: 'col-12',
label_class: 'col-xxl-10',
input_class: 'col-xxl-2'
}) }}
{% endset %}
{{ fields.dropdownField('Profile', 'field_options[' ~ key ~ ']', value, label, {
multiple: true,
add_field_html: match_invert_field,
to_add: {
'-1': __('All')
},
condition: {
'interface': 'central'
}
}) }}
TWIG, $twig_params);
}

protected function getInverted(): bool
{
return (bool) ($this->custom_field->fields['field_options'][$this->getKey() . '_invert'] ?? false);
}

public function getValue(): bool
{
$inverted = $this->getInverted();
$value = parent::getValue() ?? [];

if (!is_array($value)) {
$value = [$value];
}

// Handle special 'All' value
if (in_array(-1, $value, true)) {
return !$inverted;
}

$active_profile = $_SESSION['glpiactiveprofile']['id'] ?? null;
if ($active_profile === null) {
return false;
}
return $inverted ? !in_array($active_profile, $value, false) : in_array($active_profile, $value, false);
}
}
9 changes: 4 additions & 5 deletions src/Glpi/Asset/CustomFieldType/AbstractType.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@

use Glpi\Asset\CustomFieldDefinition;
use Glpi\Asset\CustomFieldOption\BooleanOption;
use Glpi\Asset\CustomFieldOption\ProfileRestrictOption;
use Glpi\DBAL\QueryExpression;
use Glpi\DBAL\QueryFunction;

Expand Down Expand Up @@ -70,16 +71,14 @@ public function getOptions(): array
{
return [
new BooleanOption($this->custom_field, 'full_width', __('Full width'), false),
new BooleanOption($this->custom_field, 'readonly', __('Readonly'), false),
new ProfileRestrictOption($this->custom_field, 'readonly', __('Readonly'), false),
new BooleanOption($this->custom_field, 'required', __('Mandatory'), false),
new BooleanOption($this->custom_field, 'disabled', __('Disabled'), false), // Not exposed in the UI. Only used in field order preview
new ProfileRestrictOption($this->custom_field, 'hidden', __('Hidden'), false),
];
}

/**
* @return array<string, mixed>
*/
protected function getOptionValues(bool $default_field = false): array
public function getOptionValues(bool $default_field = false): array
{
$values = [];
foreach ($this->getOptions() as $option) {
Expand Down
5 changes: 5 additions & 0 deletions src/Glpi/Asset/CustomFieldType/TypeInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ public function formatValueFromDB(mixed $value): mixed;
*/
public function getOptions(): array;

/**
* @return array<string, mixed>
*/
public function getOptionValues(bool $default_field = false): array;

/**
* Defines configured default value.
*/
Expand Down
7 changes: 3 additions & 4 deletions tests/cypress/e2e/Asset/custom_fields.cy.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ describe("Custom Assets - Custom Fields", () => {
cy.findByLabelText('Multiple values').check();
}
if (options.has('readonly')) {
cy.findByLabelText('Readonly').check();
cy.getDropdownByLabelText('Readonly').selectDropdownValue('Super-Admin');
}
if (options.has('mandatory')) {
cy.findByLabelText('Mandatory').check();
Expand Down Expand Up @@ -211,13 +211,12 @@ describe("Custom Assets - Custom Fields", () => {
cy.get('.sortable-field[data-key="name"] .edit-field').click({force: true});
cy.get('#core_field_options_editor').within(() => {
cy.findByLabelText('Full width').should('be.visible').check();
cy.findByLabelText('Readonly').should('be.visible').check();
cy.getDropdownByLabelText('Readonly').selectDropdownValue('Super-Admin');
cy.findByLabelText('Mandatory').should('be.visible').check();
cy.intercept('POST', '/ajax/asset/assetdefinition.php').as('saveFieldOptions');
cy.findByRole('button', {name: 'Save'}).click();
});
cy.get('input[name="field_options[name][full_width]"]').should('have.value', '1');
cy.get('input[name="field_options[name][readonly]"]').should('have.value', '1');
cy.get('input[name="field_options[name][readonly][]"]').should('have.value', '4');
cy.get('input[name="field_options[name][required]"]').should('have.value', '1');
});
});
Loading