Vichuploaderbundle: Expected argument of type \File\File", "string" given [FosUserBundle]

Created on 24 Jul 2016  路  26Comments  路  Source: dustin10/VichUploaderBundle

Hi,

I would like the user to be able to upload an avatar picture. So i added the following in my entity User.php:

<?php

namespace Application\Sonata\UserBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Sonata\UserBundle\Entity\BaseUser as BaseUser;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Validator\Constraints as Assert;



/**
 * @Vich\Uploadable
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity(repositoryClass="Application\Sonata\UserBundle\Entity\UserRepository")
 * @ORM\Table(name="fos_user_user")

 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */


    protected $id;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    public function __toString()
    {
        return (string) $this->getUsername();
    }

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
     *
     * @var File
     */
    private $imageFile;

    /**
     * @ORM\Column(type="string", length=255)
     *
     * @var string
     */
    private $imageName;

    /**
     * @ORM\Column(type="datetime")
     *
     * @var \DateTime
     */
    private $updatedimageAt;

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the  update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     *
     * @return User
     */
    public function setImageFile(File $image = null)
    {
        $this->imageFile = $image;

        if ($image) {
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            $this->updateimagedAt = new \DateTime('now');
        }

        return $this;
    }

    /**
     * @return File
     */
    public function getImageFile()
    {
        return $this->imageFile;
    }

    /**
     * @param string $imageName
     *
     * @return User
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * @return string
     */
    public function getImageName()
    {
        return $this->imageName;
    }
}


but when i sumbit the form i have this error:

Expected argument of type "Symfony\Component\HttpFoundation\File\File", "string" given

This is my editProfileAction()

    /**
     * @return Response|RedirectResponse
     *
     * @throws AccessDeniedException
     */
    public function editProfileAction()
    {
        $user = $this->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw $this->createAccessDeniedException('This user does not have access to this section.');
        }

        $form = $this->get('sonata.user.profile.form');
        $formHandler = $this->get('sonata.user.profile.form.handler');

        $process = $formHandler->process($user);
        if ($process) {
            $this->setFlash('sonata_user_success', 'profile.flash.updated');

            return $this->redirect($this->generateUrl('sonata_user_profile_show'));
        }

        return $this->render('SonataUserBundle:Profile:edit_profile.html.twig', array(
            'form' => $form->createView(),
            'breadcrumb_context' => 'user_profile',
        ));
    }
Support

Most helpful comment

Adding a "same problem" comment doesn't help anyone.
Opening a new issue with a quick way to reproduce would do.

All 26 comments

Up

What does your form look like? In the mean time please try and match your form with the docs. I suspect you use the wrong field for file upload.

Hi, Thank you for your response. This is how look my form:

<?php

namespace Application\Sonata\UserBundle\Form\Type;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Sonata\UserBundle\Model\UserInterface;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Form\Extension\Core\Type\FileType;
class ProfileType extends \Sonata\UserBundle\Form\Type\ProfileType
{
    private $class;
    /**
     * @param string $class The User class name
     */
    public function __construct($class)
    {
        $this->class = $class;
    }
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
              $builder
            ->add('firstname', null, array(
                'label' => 'form.label_firstname',
                'required' => false,
            ))
            ->add('lastname', null, array(
                'label' => 'form.label_lastname',
                'required' => false,
            ))
           ->add('gender', 'genemu_jqueryselect2_choice', array(
              'choices' => array(
              'm' => 'Male',
              'f' => 'Female',
              'o'=>   'Other',
              ),
             'required'    => false,
             'empty_value' => 'Choose your gender',
             'empty_data'  => null,

             ))
            ->add('dateOfBirth', 'date', [
                'required' => false,
                'label' => 'form.label_date_of_birth',
                'widget' => 'single_text',
                'format' => 'dd/MM/yyyy',
                'attr' => [
                    'class' => 'form-control input-inline datepicker',
                    'data-provide' => 'datepicker',
                    'data-datetime-format' => 'dd/MM/yyyy',
                    'placeholder' => 'dd/mm/yyy',
                ]])
            ->add('locale', 'lunetics_locale', array
                 ('label' => 'language', 'translation_domain' => 'FOSUserBundle'))

            ->add('phone', null, array(
                'label' => 'form.label_phone',
                'required' => false,
            ))
            ->add('email', 'email', [
                'required' => true,
                'label' => 'Your E-mail',
                'attr' => [
                    'class' => 'form-control',
                    'placeholder' => 'Your E-mail',
                ]])


            ->add('imageFile', 'file', array(
            ))

        ;
    }
    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => $this->class
        ));

    }
    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'application_sonata_user_profile';
    }

}

Remove the line use Symfony\Component\HttpFoundation\File\File;

Same issue here please help

I removed this line use Symfony\Component\HttpFoundation\File\File; but still having an error: Expected argument of type "Application\Sonata\UserBundle\Entity\File", "string" given .

I'm having this error only when i'm trying to upload a picture with FosUserBundle. but if i put this ->add('imageFile', 'file', array( )) in another form Type i don't have any error, the image is well uploaded. So i think there is something wrong with FosUserBundle. Do you have an idea how to fix this issue ? Thank you

vich_uploader:
    db_driver: orm # or mongodb or propel or phpcr
    mappings:
        user_avatar:
            uri_prefix:         /images/avatars
            upload_destination: '%kernel.root_dir%/../web/images/avatars'
            namer:              vich_uploader.namer_uniqid
            directory_namer:    ~
            delete_on_remove:   true
            inject_on_load:     true
            delete_on_update:   true
        article_image:
            uri_prefix:         /images/articles
            upload_destination: '%kernel.root_dir%/../web/images/articles'
            namer:              vich_uploader.namer_uniqid
            directory_namer:    ~
            delete_on_remove:   true
            inject_on_load:     true
            delete_on_update:   true

and for the form of FOSUserBundle

->add('avatar', VichFileType::class, array(
                'data_class' => null,
                'property_path' => 'avatar',
                'required' => false,
            ));
    }

Try adding inject_on_load: true

Hi Zneel, i have tried with your example, but still having the same error:Expected argument of type "Application\Sonata\UserBundle\Entity\File", "string" given

I just reviewed the doc myself, so it looks like VichUploader needs 'vich_file' instead of 'file' in your form. If you are using 2.8 or greater, please trying using the form VichFileType::class in combination with the right name space as in the docs.

i also reviewed the doc, i have tried with all the example vich_file , VichFileType::class ,file. but still getting the same error. when i tried to used vich in another form type it work perfectly, but with the edit form type of fosuserbundle it doesn't work. since 2 days i'm trying to figure out what is the problem :( . i will keep trying tomorrow.

+1

@aimeric don't know if you solved your issue but here's my code for registration form with fosuserbundle
hope it helps
RegistrationType.php

I'm actually facing the same issue. I join @aimeric 's opinion, it's all about vich with fosuserbundle. I tried the file upload with vich on other forms and it works perfectly.
@zneel thank you for your code, but unfortunately, it didn't work for me!

+1
I have the same problem

+1

I haven't try it on FOS but i got the same problem than you, and i solve it with : enctype="multipart/form-data" on my form tag
see : http://stackoverflow.com/questions/36181327/upload-image-with-vich-bundle-symfony-2

I think Fos don't add this tag on registerForm that's why u got this error.

FosUserbundle is using {{ form_start(form) }}, so the enctype option is automatically added.

It looks lile this problem is related to some specific cases. Can you tell your Symfony version and FOSUserBundle version?

Closing for missing feedback.

i have same problem any solution

Same problem, I'm trying to delete a data that is no longer exist in form (table), if i click delete then it will be deleted in a table row and if I click update it will be totally remove from table and database. My problem is when I delete data with file, error says "Uncaught PHP Exception Symfony\Component\Debug\Exception\ContextErrorException: "Catchable Fatal Error: Argument 1 passed to AppBundle\Entity\BillingEstimates::setFileDebit() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, string given, ". But if I don't put file it will successfully deleted. Please help

@jh3r0m the way your entity is working is up to you.
Moreover, the value you pass to your entity is up to you.
I can't help you in such situation

@garak thank you for trying :) . Ill try to trace it. By the way I'm just a beginner can you suggest me any article that could help me learn symfony? That would be very helpful to me as an intern

I have the same problem

Adding a "same problem" comment doesn't help anyone.
Opening a new issue with a quick way to reproduce would do.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nobady90 picture nobady90  路  3Comments

seddighi78 picture seddighi78  路  4Comments

benIT picture benIT  路  3Comments

petrjirasek picture petrjirasek  路  7Comments

smilesrg picture smilesrg  路  6Comments