jjzjj

php - Symfony2 + SonataAdmin + VichUploaderBundle - 图片上传字段

coder 2024-04-20 原文

作为 Symfony 的新手,花了最后几天的时间尝试找到一个很好的解决方案,将图像上传字段集成到 Sonata Admin 中的现有实体中。我一直在谷歌搜索并遵循可用的指南,但不幸的是我无法弄清楚。

标题中指定的设置

Symfony2 奏鸣曲管理员 VichUploaderBundle

我目前遇到以下错误:

"Catchable Fatal Error: Argument 1 passed to Beautify\BeautiesBundle\Entity\Beauty::setImageFile() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, instance of Symfony\Component\HttpFoundation\File\File given, called in /Users/gmf/symfony/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on line 438 and defined in /Users/gmf/symfony/src/Beautify/BeautiesBundle/Entity/Beauty.php line 75 "

图片上传字段正确呈现,提交后收到错误。

这是第 75 行:

/**
* 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
*/
public function setImageFile(UploadedFile $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');
    }
}

她的是我其他密切相关的文件:

实体文件:

 <?php

    // src/Beautify/BeautiesBundle/Entity/Beauty.php

    namespace Beautify\BeautiesBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\HttpFoundation\File\UploadedFile;
    use Vich\UploaderBundle\Mapping\Annotation as Vich;

    /** 
    * @ORM\Entity
    * @ORM\Table(name="beauties")
    * @ORM\HasLifecycleCallbacks
    * @Vich\Uploadable
    */

    class Beauty
    {

        /**
        * @ORM\Column(type="integer")
        * @ORM\Id
        * @ORM\GeneratedValue(strategy="AUTO")
        */
        protected $id;

        /**
        * @ORM\Column(type="string", length=100)
        */

        protected $name;

        /**
        * @ORM\Column(type="text")
        */

        protected $content;  



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

        /**
        * @ORM\Column(type="string", length=255, nullable=true, name="image_name")
        * @var string $imageName
        */
        protected $imageName;



        /**
        * @ORM\ManyToOne(targetEntity="Category", inversedBy="beauties")
        * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
        */
        protected $category;





        /**
        * 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
        */
        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 File
        */
        public function getImageFile()
        {
            return $this->imageFile;
        }

        /**
        * @param string $imageName
        */
        public function setImageName($imageName)
        {
            $this->imageName = $imageName;
        }

        /**
        * @return string
        */
        public function getImageName()
        {
            return $this->imageName;
        }






        public function __toString()
        {
            return ($this->getName()) ? : '';
        }

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

        /**
        * Set name
        *
        * @param string $name
        * @return Beauty
        */
        public function setName($name)
        {
            $this->name = $name;

            return $this;
        }

        /**
        * Get name
        *
        * @return string 
        */
        public function getName()
        {
            return $this->name;
        }

        /**
        * Set content
        *
        * @param string $content
        * @return Beauty
        */
        public function setContent($content)
        {
            $this->content = $content;

            return $this;
        }

        /**
        * Get content
        *
        * @return string 
        */
        public function getContent()
        {
            return $this->content;
        }

        /**
        * Set category
        *
        * @param \Beautify\BeautiesBundle\Entity\Category $category
        * @return Beauty
        */
        public function setCategory(\Beautify\BeautiesBundle\Entity\Category $category = null)
        {
            $this->category = $category;

            return $this;
        }

        /**
        * Get category
        *
        * @return \Beautify\BeautiesBundle\Entity\Category 
        */
        public function getCategory()
        {
            return $this->category;
        }








    }

#ADMIN 文件

<?php
// src/Beautify/BeautiesBundle/Admin/BeautyAdmin.php

namespace Beautify\BeautiesBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

use Knp\Menu\ItemInterface as MenuItemInterface;

use Beautify\CategoryBundle\Entity\Category;


class BeautyAdmin extends Admin
{
    // Fields to be shown on create/edit forms
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
        ->with('General')
        ->add('name', 'text', array('label' => 'Name'))
        ->add('content', 'textarea', array('label' => 'Content'))
        ->add('imageFile', 'file', array('label' => 'Image file', 'required' => false))
        ->end()
        ->with('Category')
        ->add('category', 'sonata_type_model', array('expanded' => true))
        ->end()
        ;
    }



    // Fields to be shown on filter forms
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
        ->add('name')
        ->add('content')
        ->add('category')
        ;
    }

    // Fields to be shown on lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
        ->addIdentifier('name')
        ->add('content')
        ->add('category')
        ->add('_action', 'actions', array(
        'actions' => array(
        'show' => array(),
        'edit' => array(),
        'delete' => array(),
        )
        ))
        ;
    }
}





**#SERVICES FILE**



report.listener:
class: Beautify\BeautiesBundle\Entity\Beauty
tags:
- { name: doctrine.event_listener, event: prePersist }
- { name: doctrine.event_listener, event: preUpdate }




    **#CONFIG.YML** 

    # Your other blocks
    vich_uploader:
    db_driver: orm

    mappings:
    beauty_image:
    uri_prefix:         /images/beauties
    upload_destination: %kernel.root_dir%/../images

非常感谢任何帮助,我会很高兴

最佳答案

您错过了 File 类的 use 语句:use Symfony\Component\HttpFoundation\File\File;

关于php - Symfony2 + SonataAdmin + VichUploaderBundle - 图片上传字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26862408/

有关php - Symfony2 + SonataAdmin + VichUploaderBundle - 图片上传字段的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  3. ruby-on-rails - Ruby on Rails - 为文本区域和图片生成列 - 2

    我是Rails的新手,所以请原谅简单的问题。我正在为一家公司创建一个网站。那家公司想在网站上展示它的客户。我想让客户自己管理这个。我正在为“客户”生成一个表格,我想要的三列是:公司名称、公司描述和Logo。对于名称,我使用的是name:string但不确定如何在脚本/生成脚手架终端命令中最好地创建描述列(因为我打算将其设置为文本区域)和图片。我怀疑描述(我想成为一个文本区域)应该仍然是描述:字符串,然后以实际形式进行调整。不确定如何处理图片字段。那么……说来话长:我在脚手架命令中输入什么来生成描述和图片列? 最佳答案 对于“文本”数

  4. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  5. ruby-on-rails - 有没有办法为 CarrierWave/Fog 设置上传进度指示器? - 2

    我在Rails应用程序中使用CarrierWave/Fog将视频上传到AmazonS3。有没有办法判断上传的进度,让我可以显示上传进度如何? 最佳答案 CarrierWave和Fog本身没有这种功能;你需要一个前端uploader来显示进度。当我不得不解决这个问题时,我使用了jQueryfileupload因为我的堆栈中已经有jQuery。甚至还有apostonCarrierWaveintegration因此您只需按照那里的说明操作即可获得适用于您的应用的进度条。 关于ruby-on-r

  6. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  7. STM32读取串口传感器数据(颗粒物传感器,主动上传) - 2

    文章目录1.开发板选择*用到的资源2.串口通信(个人理解)3.代码分析(注释比较详细)1.主函数2.串口1配置3.串口2配置以及中断函数4.注意问题5.源码链接1.开发板选择我用的是STM32F103RCT6的板子,不过代码大概在F103系列的板子上都可以运行,我试过在野火103的霸道板上也可以,主要看一下串口对应的引脚一不一样就行了,不一样的就更改一下。*用到的资源keil5软件这里用到了两个串口资源,采集数据一个,串口通信一个,板子对应引脚如下:串口1,TX:PA9,RX:PA10串口2,TX:PA2,RX:PA32.串口通信(个人理解)我就从串口采集传感器数据这个过程说一下我自己的理解,

  8. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  9. ruby-on-rails - 安全地显示使用回形针 gem 上传的图像 - 2

    默认情况下:回形针gem将所有附件存储在公共(public)目录中。出于安全原因,我不想将附件存储在公共(public)目录中,所以我将它们保存在应用程序根目录的uploads目录中:classPost我没有指定url选项,因为我不希望每个图像附件都有一个url。如果指定了url:那么拥有该url的任何人都可以访问该图像。这是不安全的。在user#show页面中:我想实际显示图像。如果我使用所有回形针默认设置,那么我可以这样做,因为图像将在公共(public)目录中并且图像将具有一个url:Someimage:看来,如果我将图像附件保存在公共(public)目录之外并且不指定url(同

  10. arrays - Ruby 数组 += vs 推送 - 2

    我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“

随机推荐