-1

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

渲染模板期间抛出异常(“注意:未定义索引:实体”)

配置.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(
    ))

新的.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());
}
4

2 回答 2

0

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

   {% for entity in entity %}

对我来说没有意义。当我有一组实体时,我通常会做什么:

   {% for entity in entities %}

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

抛出错误的代码行是什么?

于 2016-07-17T18:38:52.603 回答
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

我希望这对将来的某人有所帮助。

于 2016-07-26T20:01:58.850 回答