diff --git a/modules/json_form_widget/src/ArrayHelper.php b/modules/json_form_widget/src/ArrayHelper.php index 05900610ce..0afff950c9 100644 --- a/modules/json_form_widget/src/ArrayHelper.php +++ b/modules/json_form_widget/src/ArrayHelper.php @@ -96,24 +96,43 @@ public function arrayActionButtonCallback(array &$form, FormStateInterface $form */ public function handleArrayElement(array $definition, ?array $data, FormStateInterface $form_state, array $context): array { // Extract field name from field definition and min items from field schema. - $field_name = $definition['name']; $min_items = $definition['schema']->minItems ?? 0; $context_name = self::buildContextName($context); $item_count = $this->getItemCount($context_name, count($data ?? []), $min_items, $form_state); - $is_required = in_array($field_name, $this->builder->getSchema()->required ?? []); + $is_required = in_array($definition['name'], $this->builder->getSchema()->required ?? []); + + // Build the parent fieldset. + $element = $this->buildArrayParentElement($definition, $is_required, $context_name); // Build the specified number of field item elements. $items = []; for ($i = 0; $i < $item_count; $i++) { - $property_required = $is_required && ($i < $min_items); - $items[] = $this->buildArrayItemElement($definition, $data[$i] ?? NULL, $form_state, array_merge($context, [$i]), $property_required); + $item = $this->buildArrayItemElement($definition, $data[$i] ?? NULL, $form_state, array_merge($context, [$i])); + $item['#required'] = $is_required && ($i < $min_items); + $items[] = $item; } + $element[$definition['name']] = $items; + return $element; + } - // Build field element. + /** + * Build the parent fieldset for an array. + * + * @param array $definition + * Field definition. + * @param bool $is_required + * Whether the field is required. + * @param string $context_name + * Field context name. + * + * @return array + * Render array for the array parent element. + */ + protected function buildArrayParentElement($definition, $is_required, $context_name) { $element = [ '#type' => 'fieldset', - '#title' => ($definition['schema']->title ?? $field_name), + '#title' => ($definition['schema']->title ?? $definition['name']), '#description' => ($definition['schema']->description ?? ''), '#description_display' => 'before', '#prefix' => '