Array of checkboxes give unexpected values at submit event

Viewed 58

I want to store an array of 9 checkboxes each related to same entity in my database.

Exemple of desired data

['0','0','1','1','1','1','1','1','1'] #Array[]|length = 9
['1','0','0','0','0','0','0','0','0']
['0','1','0','0','0','0','0','0','0']
['1','1','0','0','0','0','0','0','0']
['2','0','0','0','0','0','0','0','0']
['0','2','0','0','0','0','0','0','0']
['0','0','2','0','0','0','0','0','0']
['0','0','2','1','0','0','0','0','0']
['1','0','2','0','0','0','0','0','0']

Here that's i've got for these corresponding examples

['0','0']
['1','0']
['0','1']
['1','1']
['2','0']
['0','0']
['0','2']
['0','0','2'] #something i cant understand
['1','0','2']

I use basic ChoiceType

$builder
        ->add('recipe', ChoiceType::class, [
          'choices' => [],
          'multiple' => true,
          'expanded' => true,
          'label' => 'Craft',
        ])
;

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $craft = $event->getData();
        $recipe = $craft['recipe'];

        dump($recipe); # good at this point
});

$builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
        $craft = $event->getData();
        $recipe = $craft['recipe'];

        dump($recipe); # bad array...
});

Accorded to symfony documentation, between these two events, data get normalized. (reference)

I would like to customize normalization step accorded to my FormType, and only thing ive found after few hours is file located at symfony/form/ChoiceList/ArrayChoiceList.php which can be my problem. (ArrayChoiceList on github)

1 Answers

ChoiceType, imho, is the wrong form type for this (and it's a common mistake), since it's used to select entries from a larger set of entries. Where usually order isn't important and non-selected entries are omitted.

Depending on what actually is selected, one in the following (not necessarily complete) list may serve you better:

A. entries are uniform

Usual use case for the CollectionType. Leaving the default for the CollectionType's options allow_add and allow_delete on false will prevent items from being added or removed. However, rendering might be more difficult. the CollectionType's entry_type would probably be ChoiceType (with multiple set to false!) with probably similar choices as before ... or CheckboxType, however the values might be hard to set here.

B. entries are different

It might be better to manually add 9 form elements manually, and set the property_path of each to recipe[N] where N is a number between 0 and 8, defining where to get and where to set the specific value.

Related