Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 : How to upload a file without Doctrine?

I use Symfony2.3. I have a form like this :

<form action="{{ path("member_update") }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form.pic) }}
    ...
    {{ form_widget(form._token) }}
</form>

and i want to upload user pictures in a directory.Then i use this in controller :

$member , $form , $dm is defined...

if ($form->isValid()) {
        // Handle profile picture upload process
        $uploadDir=dirname($this->container->getParameter('kernel.root_dir')) . '/web/bundles/mybundle/myfiles';
        $form['pic']->getData()->move($uploadDir,$member->getId());
        // End of upload

        $dm->persist($member);
        $dm->flush();
        return $this->redirect($this->generateUrl("member_profile"));
    }

It must work,but i see this error:

Exception: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

1. in pathToMyProject...\vendor\symfony\symfony\src\Symfony\Component\HttpKernel\DataCollector\DataCollector.php line 27
2. at serialize(.....

What's the problem??!

like image 896
ABS Avatar asked Aug 21 '13 13:08

ABS


1 Answers

The problem solved! I change this line in MemberType :

$builder->add('pic','file');

to this :

$builder->add('pic','file', array('mapped'=>false));

My mistake was that i must explain the "pic" field is not mapped to the Entity(or Document in Mongo,as my project). Else Symfony kernel try to put the value of "pic" in a field of Entity. And i have not any field that hold a file! I upload the picture in a directory and store only path to the picture within the entity. When i changed this,the problem solved easily! :-) So keep in mind to explain all things clearly to Symfony!

like image 188
ABS Avatar answered Oct 29 '22 16:10

ABS