dachcom-digital / pimcore-formbuilder

Pimcore Formbuilder - create forms easily!
Other
91 stars 47 forks source link

[BUG] Save choice_meta in ChoicesTransformer #425

Closed c4meleon closed 7 months ago

c4meleon commented 10 months ago
Q A
Bug report? yes
Feature request? yes
BC Break report? no
RFC? no

Please update this code like this:

namespace FormBuilderBundle\Transformer;

class ChoicesTransformer implements OptionsTransformerInterface
{
    public function transform(mixed $values, ?array $optionConfig = null): array
    {
        $parsedChoices = [];
        foreach ($values as $choice) {
            if (isset($choice[0])) {
                $groupName = $choice[0]['name'];
                foreach ($choice as $index => $choiceGroup) {
                    $parsedChoices[$groupName][$choiceGroup['option']] = json_encode($this->prepareChoiceData($choiceGroup['choice_meta']));
                }
            } else {
                $parsedChoices[$choice['option']] = json_encode($this->prepareChoiceData($choice));
            }
        }

        return $parsedChoices;
    }

    public function reverseTransform(mixed $values, ?array $optionConfig = null): array
    {
        $parsedChoices = [];

        foreach ($values as $choiceKey => $choiceValue) {
            if (is_array($choiceValue)) {
                foreach ($choiceValue as $groupOption => $groupValue) {
                    $parsedChoices[] = $this->reversePrepareChoiceData($groupOption, json_decode($groupValue, true), $choiceKey);
                }
            } else {
                $parsedChoices[] = $this->reversePrepareChoiceData($choiceKey, json_decode($choiceValue, true));
            }
        }

        return $parsedChoices;
    }

    private function prepareChoiceData(array $choice): array
    {
        return [
            'value' => $choice['value'],
            'choice_meta' => $choice['choice_meta'] ?? null,
        ];
    }

    private function reversePrepareChoiceData(string $option, array $choice, ?string $name = null): array
    {
        $result = [
            'option' => $option,
            'value' => $choice['value'],
        ];

        if ($name !== null) {
            $result['name'] = $name;
        }

        if (isset($choice['choice_meta'])) {
            $result['choice_meta'] = $choice['choice_meta'];
        }

        return $result;
    }
}
solverat commented 9 months ago

Hi @c4meleon, could you explain a bit more why we should do this? There is a dedicated ChoicesMetaTransformer which is handling the choice_meta section. However, choice meta data is only available for dynamic fields (you could recognize dynamic fields as extensions to given fields) and currently only available in choice field, where it allows you to add additional data to your choice element.