FriendsOfSymfony / FOSRestBundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony
http://symfony.com/doc/master/bundles/FOSRestBundle/index.html
MIT License
2.79k stars 704 forks source link

FOS rest-bundle + sonata media-bundle #1677

Open mustapha72 opened 7 years ago

mustapha72 commented 7 years ago

Hello,

Is there a simple solution to handle a POST request that contain an upload file field (+ some other fields) using REST API and sonata media bundle.

My entity have a relation with sonata media bundle by this file.

Entity: `/**

Form type:

$builder ->add('title') ->add('description') ->add('cover', 'sonata_media_type', array( 'context' => 'network', 'provider' => 'sonata.media.provider.image' )) ;

ishapkin commented 7 years ago

Same problem, but I can't solved this correctly. May be you already received right solution. But my wrong upload consist of:

file FormManager.php - it is service 'app.form.manager'

class FormManager {
     /**
     * @param Request $request
     * @return bool|Media
     */
    public function wrongUploadMedia(Request $request) {

        $media = false;

        if($file = $request->files->get('binaryContent')) {
            /** @var Media $media */
            $media = $this->container->get('sonata.media.manager.media')->create();
            // $this->provider = 'sonata.media.provider.file';
            $media->setProviderName($this->provider);
            $media->setBinaryContent($file);
            //-> for form extra fields solved
            $request->files->remove('binaryContent');
            $this->container->get('sonata.media.manager.media')->save($media);
        }

        return $media;
    }
}

In controller I use it this:

public function postAction(Request $request, ProgramParticipant $entity) {
        $entity = new myEntity();
        $media = $this->get('app.form.manager')->wrongUploadMedia($request);
        $form = $this->createForm(new myEntityType(), $entity, array("method" => $request->getMethod()));
        $form->handleRequest($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            if($media instanceof Media) {
                $entity->setMedia($media);
            }
            $em->persist($entity);
            $em->flush();
            return $entity;
        }

        return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR);
    }
mustapha72 commented 7 years ago

I already resolved but thank you anyway

ishapkin commented 6 years ago

@mustapha72, do you can show your solution?