symfony adding file image constraints to form

let’s say you want to constraint what people are uploading and you don’t want to use assert statements in the entity. you can do it in the formbuilder

use Symfony\Component\Validator\Constraints\File;
...
$form = $this->createFormBuilder($entity)
            ->add('logo', FileType::class,
                array(
                    'label' => false,
                    'attr' => array(
                        'accept' => "image/jpeg, image/png"
                    ),
                    'constraints' => [
                        new File([
                            'maxSize' => '2M',
                            'mimeTypes' => [
                                'image/jpeg',
                                'image/png',
                            ],
                            'mimeTypesMessage' => 'Please upload a JPG or PNG',
                        ])
                    ]
                )
            )

Author: bpeh

Bernard Peh is a great passioner of web technologies and one of the co-founder of Sitecritic.net Website Design and Reviews. He works with experienced web designers and developers everyday, developing and designing commercial websites. He specialises mainly in SEO and PHP programming.