Skip to content

Commit 88fdcf9

Browse files
committed
add file error upload checker
1 parent b1e3fdc commit 88fdcf9

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/Form/Type/ImageType.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,11 @@
2323
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
2424
use Symfony\Component\Form\Extension\Core\Type\TextType;
2525
use Symfony\Component\Form\FormBuilderInterface;
26+
use Symfony\Component\Form\FormError;
2627
use Symfony\Component\Form\FormEvent;
2728
use Symfony\Component\Form\FormEvents;
29+
use Symfony\Component\HttpFoundation\File\UploadedFile;
30+
use Symfony\Component\OptionsResolver\OptionsResolver;
2831

2932
/**
3033
* @author Ishmael Doss <nukboon@gmail.com>
@@ -92,6 +95,16 @@ public function buildForm(FormBuilderInterface $builder, array $options)
9295
'required' => false,
9396
])
9497
;
98+
99+
if ($options['check_file_error']) {
100+
$builder->get('file')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
101+
$file = $event->getData();
102+
103+
if ($file && $file instanceof UploadedFile && false === $file->isValid()) {
104+
$event->getForm()->addError(new FormError($file->getErrorMessage()));
105+
}
106+
});
107+
}
95108
}
96109

97110
/**
@@ -108,6 +121,17 @@ public function convertBase64ImageListener(FormEvent $event): void
108121
}
109122
}
110123

124+
/**
125+
* {@inheritdoc}
126+
*/
127+
public function configureOptions(OptionsResolver $resolver): void
128+
{
129+
parent::configureOptions($resolver);
130+
131+
// should override with your own validator
132+
$resolver->setDefault('check_file_error', true);
133+
}
134+
111135
/**
112136
* {@inheritdoc}
113137
*/

0 commit comments

Comments
 (0)