Skip to content
Advertisement

Symfony – ChoiceType with multiple and resetViewTransformers returns invalid_message

We have upgraded our project to Symfony 4.4.35 2 months ago and now I noticed a strange behavior. When I use ChoiceType with the following configuration, the form returns error (This value is not valid):

$builder->add('items', ChoiceType::class, [
    'required' => FALSE,
    'multiple' => TRUE,
]);
$builder->get('items')->resetViewTransformers();

The POST:

form[items][0]: "val1"
form[items][1]: "val2"

Can someone tell me what has changed? I have tried to inspect ChoiceType.php, and find out the problem is here:

$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use (&$unknownValues, $messageTemplate) {
    if (count($unknownValues) > 0) {
        // here is append error to form
    }
});

The question is: How to create multiselect with variable length and custom values?

Advertisement

Answer

I had to use SymfonyComponentFormExtensionCoreTypeCollectionType with option allow_add.

$builder->add('items', CollectionType::class, [
    'allow_add' => TRUE,
]);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement