简体   繁体   English

Symfony 2 Sonata Media捆绑包:保存媒体文件图像而无需Sonata管理员

[英]Symfony 2 Sonata Media bundle: saving media file image without sonata admin

I have using the Sonata Admin Bundle and Sonata Media Bundle. 我正在使用Sonata Admin捆绑包和Sonata媒体捆绑包。 It's great, but i have the problem about using Media. 很好,但是我有使用Media的问题。 https://sonata-project.org/bundles/media/2-2/doc/index.html 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. 示例我有一个Post Document,在Post中我有$ image变量,而targetDocument是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时,必须上传图像文件,并且在保存Post之前,必须先将上传的图像文件保存到Media Entity,然后将Post的$ image指向刚刚保存的Media Entity。

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 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM