Esta página descreve as classes que podem ser usadas para criar uma visualização de configuração do widget com campos de configuração personalizados. A exibição de configuração do widget é a parte do widget que permite ao usuário configurar os parâmetros do widget para presentation.
Classe primária de widget, estende a classe base de todos os widgets do painel - CWidget. Necessário para substituir o comportamento padrão do widget.
A classe Widget deve estar localizada no diretório raiz do widget (por exemplo, ui/modules/my_custom_widget).
Exemplo de Widget.php
<?php
namespace Modules\MyCustomWidget;
use Zabbix\Core\CWidget;
class Widget extends CWidget {
public const MY_CONSTANT = 0;
função pública getTranslationStrings(): array {
retorna [
'class.widget.js' => [
'Sem dados' => _('Sem dados')
]
];
}
}A classe WidgetForm estende a classe padrão CWidgetForm e contém um conjunto de campos CWidgetField que são necessários para definir a estrutura de armazenamento da configuração do widget no banco de dados e manipular a validação de entrada.
A classe WidgetForm deve estar localizada no diretório includes. Se a classe tiver um nome diferente, o nome deverá ser especificado no parâmetro widget/form_class no arquivo manifest.json.
Exemplo de includes/WidgetForm.php
<?php
namespace Modules\MyCustomWidget\Includes;
use Modules\MyCustomWidget\Widget;
use Zabbix\Widgets\{
CWidgetField,
CWidgetForm
};
use Zabbix\Widgets\Fields\{
CWidgetFieldMultiSelectItem,
CWidgetFieldTextBox,
CWidgetFieldColor
};
class WidgetForm extends CWidgetForm {
função pública addFields(): self {
return $this
->addField(
(novo CWidgetFieldMultiSelectItem('itemid', _('Item')))
->setFlags(CWidgetField::FLAG_NOT_EMPTY | CWidgetField::FLAG_LABEL_ASTERISK)
->setMultiple(false)
->setFilterParameter('numeric', true)
)
->addField(
new CWidgetFieldTextBox('description', _('Description'))
)
->addField(
(new CWidgetFieldColor('chart_color', _('Color')))->setDefault('FF0000')
);
}
}A classe CWidgetFormView é necessária para especificar a lógica de apresentação dos campos definidos na classe WidgetForm, determinando sua aparência e comportamento quando renderizados na exibição de configuração.
A classe CWidgetFormView é compatível com os seguintes métodos:
A classe CWidgetFormView deve estar localizada no diretório views.
Exemplo de views/widget.edit.php
<?php
/**
* Minha visualização de formulário de widget personalizado.
*
* @var CView $this
* @var array $data
*/
use Zabbix\Widgets\Fields\CWidgetFieldGraphDataSet;
(novo CWidgetFormView($data))
->addField(
new CWidgetFieldMultiSelectItemView($data['fields']['itemid'], $data['captions']['items']['itemid'])
)
->addField(
new CWidgetFieldTextBoxView($data['fields']['description']),
'js-advanced-configuration'
)
->addField(
new CWidgetFieldColorView($data['fields']['chart_color']),
'js-advanced-configuration'
)
->includeJsFile('widget.edit.js.php')
->addJavaScript('my_widget_form.init('.json_encode([
'color_palette' => CWidgetFieldGraphDataSet::DEFAULT_COLOR_PALETTE
], JSON_THROW_ON_ERROR).');')
->show();A JavaScript class can be used to add dynamic behavior and interactivity to the widget configuration view. For example, you can initialize a color picker, defined in the CWidgetFormView class.
The JavaScript class should be loaded with the form, therefore it should be referenced in the CWidgetFormView class by using the methods includeJsFile() and addJavaScript().
In the example below, a singleton class instance is immediately created and stored under the window.my_custom_widget_form name. Thus, opening the form for the second time will re-create the instance.
The JavaScript class should be located in the views directory.
views/widget.edit.js.php example
<?php
use Modules\MyCustomWidget\Widget;
?>
window.my_custom_widget_form = new class {
init({color_palette}) {
colorPalette.setThemeColors(color_palette);
for (const colorpicker of jQuery('.<?= ZBX_STYLE_COLOR_PICKER ?> input')) {
jQuery(colorpicker).colorpicker();
}
const overlay = overlays_stack.getById('widget_properties');
for (const event of ['overlay.reload', 'overlay.close']) {
overlay.$dialogue[0].addEventListener(event, () => { jQuery.colorpicker('hide'); });
}
}
};The CWidgetField class is a base class from which all form field classes (CWidgetFieldCheckBox, CWidgetFieldTextArea, CWidgetFieldRadioButtonList, etc.) are inherited. Classes extending CWidgetField are responsible for receiving, saving, and validating widget configuration values.
The following CWidgetField classes are available.
| CWidgetField class | Database field type | Description |
|---|---|---|
| CWidgetFieldCheckBox | int32 | Single checkbox. |
| CWidgetFieldCheckBoxList | array of int32 | Multiple checkboxes under a single configuration field. |
| CWidgetFieldColor | string | Color selection field. |
| CWidgetFieldDatePicker | string | Date selection field. |
| CWidgetFieldHostPatternSelect | string | Multiselect field that allows to select one or multiple hosts. Supports defining host name patterns (all matching hosts will be selected). |
| CWidgetFieldIntegerBox | int32 | Field to enter an integer. Can be used to configure minimum and maximum values. |
| CWidgetFieldLatLng | string | Text box that allows to enter comma-separated latitude, longitude, and map zoom level. |
| CWidgetFieldMultiSelectAction | ID | Multiselect field for selecting actions (from the list of actions defined in the Alerts → Actions). |
| CWidgetFieldMultiSelectGraph | ID | Multiselect field for selecting custom graphs. |
| CWidgetFieldMultiSelectGraphPrototype | ID | Multiselect field for selecting custom graph prototypes. |
| CWidgetFieldMultiSelectGroup | ID | Multiselect field for selecting host groups. |
| CWidgetFieldMultiSelectHost | ID | Multiselect field for selecting hosts. |
| CWidgetFieldMultiSelectItem | ID | Multiselect field for selecting items. |
| CWidgetFieldMultiSelectItemPattern | ID | Multiselect field for selecting item patterns. |
| CWidgetFieldMultiSelectItemPrototype | ID | Multiselect field for selecting item prototypes. |
| CWidgetFieldMultiSelectMap | ID | Multiselect field for selecting maps. |
| CWidgetFieldMultiSelectMediaType | ID | Multiselect field for selecting media types. |
| CWidgetFieldMultiSelectOverrideHost | ID | Multiselect field for selecting a data source (dashboard or other widget) containing a host for which the widget can display data. |
| CWidgetFieldMultiSelectService | ID | Multiselect field for selecting services. |
| CWidgetFieldMultiSelectSla | ID | Multiselect field for selecting SLAs. |
| CWidgetFieldMultiSelectUser | ID | Multiselect field for selecting users. |
| CWidgetFieldNumericBox | string | Field to enter a float number. |
| CWidgetFieldRadioButtonList | int32 | Radio box group that consists of one or more radio boxes. |
| CWidgetFieldRangeControl | int32 | Slider to select an integer type value. |
| CWidgetFieldReference | string | Creates a unique identifier for this widget on dashboard. It is used to reference this widget from other widgets. |
| CWidgetFieldSelect | int32 | Dropdown select box. |
| CWidgetFieldSeverities | array of int32 | CWidgetFieldCheckBoxList preset with trigger severities. |
| CWidgetFieldTags | array of (string, int32, string) | Allows to configure one or more tag filter rows. |
| CWidgetFieldTextArea | string | Text area for entering multi-line text. |
| CWidgetFieldTextBox | string | Text box for entering single-line text. |
| CWidgetFieldTimePeriod | array of string | Time period selecting field. |
| CWidgetFieldTimeZone | string | Dropdown with timezones. |
| CWidgetFieldThresholds | array of (string, string) | Allows configuring color and number pairs. |
| CWidgetFieldUrl | string | Text box that allows to enter URLs. |
The following CWidgetField classes have been created for particular widgets. These classes have very specific use cases, but they can also be reused if needed.
| CWidgetField class | Database field type | Description |
|---|---|---|
| CWidgetFieldColumnsList | array of (multiple mixed) | For Top hosts widget. Create a table with custom columns of allowed types. |
| CWidgetFieldNavTree | string | For Map navigation tree widget. Replaces widget view in edit mode with the map selection tree. |