Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
Closed
@BoShurik

Description

@BoShurik
Issue body actions

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

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.