Skip to content

[Form][HttpFoundation] Filtering FileBag removes items from CollectionType with FileType #35100

Closed
@BoShurik

Description

@BoShurik

Symfony version(s) affected: all

Description
Similar to #24546

When file is not uploaded I get previously defined one but it's impossible to separate deletion of collection item and not uploading a file

How to reproduce

class IssueType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('files', CollectionType::class, [
                'entry_type' => FileType::class,
                'entry_options' => [
                    'required' => false,
                ],
                'allow_add' => true,
                'allow_delete' => true,
            ])
        ;

        $builder->get('files')->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
            $data = (array)$event->getForm()->getData();
            $exist = [];
            foreach ((array)$event->getData() as $index => $item) {
                // Expect 0 => null for not uploaded file
                if ($item !== null) {
                    $data[$index] = $item; // Replace file
                }

                $exist[$index] = true;
            }

            $keys = array_keys($data);
            foreach ($keys as $key) {
                if (!isset($exist[$key])) {
                    unset($data[$key]); // Remove deleted element
                }
            }

            $event->setData($data);
        });
    }
}

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