渲染上传图片时出错VichUploaderBundle [symfony2.8]

时间:2016-07-17 17:46:27

标签: php symfony orm twig vichuploaderbundle

我使用Bundle VichUploader上传图片。图片很好地保存在网页目录中,但是当我试图渲染它时,我有以下错误:

  

在渲染模板期间抛出了异常   ("注意:未定义的索引:实体")

Config.yml

vich_uploader:
    db_driver: orm
    mappings:
        product_image:
            uri_prefix:         /userprofile/pictures
            upload_destination: %kernel.root_dir%/../web/bundles/flyplatform/userprofile/pictures
            namer: vich_uploader.namer_uniqid
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true

post.php中

<?php

namespace FLY\BookingsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Application\Sonata\UserBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Form\Type\VichImageType;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Form\Extension\Core\Type\FileType;
/**
 * Post
 *
 * @ORM\Table(name="post")
 * @ORM\Entity(repositoryClass="FLY\BookingsBundle\Entity\PostRepository")
 * @Vich\Uploadable
 */
class Post
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */

    private $id;

    /**
     *
     *
     * @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
     *
     * @var File
     */
    private $imageFile;



    /**
     * 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->updatedAt = 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;
    }

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

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


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

}

PostType.php

$builder

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

new.html.twig

 {% for entity in entity %}
                                    <img src="{{ vich_uploader_asset(entity, 'imageFile') }}" alt="{{ product.name }}" />
                                    {% endfor %}

添加

PostController.php

/**
     * Creates a new Post entity.
     *
     * @Route("/", name="post_create")
     * @Method("POST")
     * @Secure(roles="ROLE_USER")
     * @Template("FLYBookingsBundle:Post:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $user = $user = $this->getUser();
        $entity = new Post();
        $entity->setEmail($user);
        $form = $this->createForm(PostType::class,$entity);
        $form->handleRequest($request);
        if ($form->isValid()) {
            $userManager = $this->container->get('fos_user.user_manager');
            $usr = $userManager->findUserByUsername($this->container->get('security.context')
                ->getToken()
                ->getUser());
            $entity->setUsername($usr);

            $user = $this->getUser();
            $entity->setUser($user);

            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('post_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form' => $form->createView(),
        );
    }



/**
 * Displays a form to create a new Post entity.
 *
 * @Route("/new", name="post_new")
 * @Method("GET")
 * @Template()
 */
public function newAction()
{
    $entity = new Post();
    $form = $this->createCreateForm($entity);



    return array( 'entity' => $entity,'form' => $form->createView());
}

2 个答案:

答案 0 :(得分:0)

我没有看到循环浏览一个项目的目的,所以:

   {% for entity in entity %}

对我没有意义。当我有一组实体时,我会毫无帮助地做什么:

   {% for entity in entities %}

实体是传递给模板的对象数组。 控制器的代码是什么?这样我们就可以看到您传递给模板的参数。 product指的是什么?

抛出错误的代码是什么?

答案 1 :(得分:0)

我终于找到了解决问题的方法。当我检查元素时,我注意到图像的路径是这样的:/userprofile/pictures,但实际上它应该是这样的:/symfony/web/bundles/flyplatform/userprofile/pictures/。我将uri_prefix: /userprofile/pictures更改为此uri_prefix: /symfony/web/bundles/flyplatform/userprofile/pictures/

<img src="{{ vich_uploader_asset(entity, 'imageFile') }}" alt="{{entity.imageName }}" />

vich_uploader:
    db_driver: orm
    mappings:
        product_image:
            uri_prefix: /symfony/web/bundles/flyplatform/userprofile/pictures/
            upload_destination: %kernel.root_dir%/../web/bundles/flyplatform/userprofile/pictures
            namer: vich_uploader.namer_uniqid
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true

我希望这将有助于将来的某个人。