['nested-dictionary-item', 'collapsible']]; /** @var array Items in the nested dictionary property */ protected array $items = []; /** @var ?SubmitButtonElement Remove button for the nested dictionary property*/ private ?SubmitButtonElement $removeButton = null; public function __construct(string $name, array $items, $attributes = null) { $this->items = $items; $this->getAttributes()->add([ 'data-toggle-element' => 'legend', 'data-visible-height' => 0 ]); parent::__construct($name, $attributes); } protected function assemble(): void { $this->addElement('text', 'key', [ 'label' => $this->translate('Key'), 'required' => true, 'class' => 'autosubmit' ]); $id = $this->getPopulatedValue('id'); if ($id === null) { $id = uniqid('id-'); } $this->addElement('hidden', 'id', ['value' => $id]); $this->getAttributes()->set('id', $id); $label = $this->getElement('key')->getValue(); if ($label === null) { $label = $this->translate('New Item'); } $this->setLabel($label); if ($this->removeButton !== null) { $this->addHtml(new HtmlElement( 'div', null, $this->removeButton->setLabel(new Icon('trash')) ->setAttribute('formnovalidate', true) ->setAttribute('class', ['remove-button']) ->add(Text::create(' ' . $this->translate('Remove'))) )); } $this->addElement(new Dictionary('var', $this->items, ['class' => 'no-border'])); } /** * Set the remove button. * * @param ?FormElement $removeButton * * @return $this */ public function setRemoveButton(?FormElement $removeButton): static { $this->removeButton = $removeButton; return $this; } /** * Prepare the nested dictionary item value for display * * @param array $nestedItems * @param array $property * * @return array */ public static function prepare(array $nestedItems, array $property): array { $nestedValues = []; foreach ($nestedItems as $nestedItem) { if (isset($property[$nestedItem['key_name']]) && ! empty($property[$nestedItem['key_name']])) { $nestedItem['value'] = $property[$nestedItem['key_name']]; } $nestedValues[] = $nestedItem; } if (isset($property['key']) && str_starts_with($property['key'], NestedDictionary::UNDEFINED_KEY)) { $property['key'] = null; } return [ 'key' => $property['key'], 'var' => Dictionary::prepare($nestedValues) ]; } /** * Get the nested dictionary item value * * @return NestedDictionaryItemDataType */ public function getItem(): array { $this->ensureAssembled(); $key = $this->getElement('key')->getValue(); $values = []; $values['key'] = $key; $values['value'] = $this->getElement('var')->getDictionary(); return $values; } }