I have using the Sonata Admin Bundle and Sonata Media Bundle. It's great, but i have the problem about using Media. https://sonata-project.org/bundles/media/2-2/doc/index.html
Example I have a Post Document, in Post I have $image variable with targetDocument is Media. And When I create new Post, I must upload the image file, and before save Post, I must save the upload image file to Media Entity first and then I pointing the $image of Post to the Media Entity just been saved.
Post Document:
<?php
namespace Acme\Bundle\PostBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @MongoDB\Document(repositoryClass="Acme\Bundle\PostBundle\Repository\PostRepository")
*/
class Post
{
/**
* @MongoDB\Id
*/
protected $id;
/**
* @MongoDB\String
*/
protected $name;
/**
* @MongoDB\ReferenceOne(targetDocument="Application\Sonata\MediaBundle\Document\Media", nullable=true )
*/
protected $image;
Can we have any way to access the Media Entity and save the upload file to it in Post Document function. I had read this but it not help more.
https://sonata-project.org/bundles/media/master/doc/reference/form.html
The answer is here:
In above code, we must save the upload image to media first and then pointed it to the post:
$mediaManager = $this->container->get('sonata.media.manager.media');
$media = new Media();
$media->setBinaryContent($uploadImage);
$media->setContext('default');
$media->setProviderName('sonata.media.provider.image');
$mediaManager->save($media);
$post->setImage($media);
print_r($media);exit;