Closed
Description
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);
});
}
}