Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Form] collection of choices with delete_empty ignores invalid items #37660

Closed
@guilliamxavier

Description

@guilliamxavier

Symfony version(s) affected: 4.4.10+, 5.2.3

Description
When submitting invalid data to a form for a collection of choices, there's no error if the delete_empty option is enabled.

How to reproduce

First, run composer require symfony/form
Then, execute this file:

<?php
require __DIR__.'/vendor/autoload.php';
use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

$name = 'items';
$choices = [
    'foo',
    'bar',
    'qux',
];
$form = Forms::createFormFactory()->createBuilder()
    ->add($name, CollectionType::class, [
        'allow_add' => true,
        'delete_empty' => true, // *** THIS LINE
        'entry_type' => ChoiceType::class,
        'entry_options' => [
            'choices' => array_combine($choices, $choices),
        ],
    ])
    ->getForm();

$form->submit([
    $name => [
        'foo',
        'x', // *** INVALID
        'qux',
        '', // empty
    ],
]);

echo preg_replace('/( => )\n +/', '$1', var_export($form->getData(), true)), "\n";
var_dump($form->isValid());
echo $form->getErrors(true, false);

Output:

array (
  'items' => array (
    0 => 'foo',
    2 => 'qux',
  ),
)
bool(true)

i.e. the invalid item isn't there in the final data (like the empty one), the form says it's valid, no errors.

(Precision: I'm not sure about the fact that the invalid item is "missing", but I would have expected a form error.)

To compare, if I disable/remove the delete_empty option, then the output is:

array (
  'items' => array (
    0 => 'foo',
    2 => 'qux',
    3 => NULL,
  ),
)
bool(false)
items:
    1:
        ERROR: This value is not valid.

i.e. the invalid item is still not there (unlike the empty one now), but the form says it's not valid, with an error.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions