1

I have file field with required = false, multiple=multiple. Everything works fine, but if file input is empty, symfony2 show me this error.

Error: Call to a member function guessExtension() on null

Here is my form type:

->add('file', 'file', array(
                'multiple' => 'multiple',
                'data_class' => null,
                'required' => false,
                'mapped' => false,
                'attr' => array(
                    'maxSize' => '1024k',
                    'accept' => 'image/*',
                )
            ))

Upload function:

private function uploadImg($files)
    {
        $path = array();
        foreach ($files as $file) {
            $extension = $file->guessExtension();
            if (!$extension) {
                $extension = 'bin';
            }
            $randomName = 'image' . date('Y-m-d-H-i-s') . uniqid() . '.' . $extension;
            $file->move('uploads/images/', $randomName);
            $path[] = $randomName;
        }
        return $path;
    }

How can I check if file input is empty?

$form['file']->getData(); every time returns Array

2
  • You can try with count. Since multiple is set to true you will always end up receiving an array, whether it's empty or not. Commented Aug 23, 2015 at 19:01
  • Thanks, but it works only if input is totally empty or has 2 or more files. Commented Aug 23, 2015 at 19:11

2 Answers 2

1

You can use continue to skip empty files

    foreach ($files as $file) {
        if(!$file) {
            continue; //skip
        }

        $extension = $file->guessExtension();
        if (!$extension) {
            $extension = 'bin';
        }
        $randomName = 'image' . date('Y-m-d-H-i-s') . uniqid() . '.' . $extension;
        $file->move('uploads/images/', $randomName);
        $path[] = $randomName;
    }
Sign up to request clarification or add additional context in comments.

Comments

0

For Symfony 3, I used this method and working fine.

use Symfony\Component\HttpFoundation\File\UploadedFile;

public function updateAction(...){
  // $image is Entity property, change accordingly.
  $file = $item->getImage();
  if ($file instanceof UploadedFile) {
     ... upload code
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.