symfony2文件在表单错误时丢失 [英] symfony2 file lost upon form error

查看:135
本文介绍了symfony2文件在表单错误时丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当我的上传表单遇到错误时,我正在使用与教义相关的文件上传的标准实现,如symfony2网站教程中的示例。验证,并将用户发回给带有错误消息的表单,它会丢失选择上传的文件,但是如果我的var_dump我的$ entity->文件,我可以看到它有文件...

  //如果表单有效,做一些东西...如果没有:
else {

// var_dump ($实体 - >文件); //这样做,我得到我的文件
// die;

//获取并检查父选择的文件夹
$ entity-> setFolder($ this-> checkFolderId($ request-> request-> get(' ))); //将导致die()如果文件夹不属于此公司

$ folders = $ this-> getFolders();

return $ this-> render('BizTVMediaManagementBundle:Image:new.html.twig',array(
'entity'=> $ entity,
'form' = $ form-> createView(),
'folders'=> $ folders,
'fileExists'=> $ fileExists,
));

}

此后放入枝杈视图,没有什么在文件字段中。



这是我的实体...

 <?php 

命名空间BizTV\MediaManagementBundle\Entity;

使用Doctrine\ORM\Mapping作为ORM;
使用Symfony\Component\Validator\Constraints作为Assert;

/ **
* BizTV \MediaManagementBundle\Entity\Image
*
* @ ORM\Table(name =image)
* @ ORM\Entity
* @ ORM\HasLifecycleCallbacks
* /
class Image
{
/ **
* @var integer $ id
*
* @ ORM\Column(name =id,type =integer)
* @ ORM\Id
* @ ORM\GeneratedValue (strategy =AUTO)
* /
private $ id;

/ **
* @var string $ name

*
* @ ORM\Column(name =name,type = string,length = 255)
* @ Assert\NotBlank
* /
private $ name;

/ **
* @var整数$ width
*
* @ ORM\Column(name =width,type =integer)
* /
private $ width;

/ **
* @var整数$ height
*
* @ ORM\Column(name =height,type =integer)
* /
private $ height;

/ **
* @ ORM\Column(type =string,length = 255,nullable = true)
* /
private $ path;

/ **
* @var对象BizTV\BackendBundle\Entity\company
*
* @ ORM\ManyToOne(targetEntity =BizTV
* @ ORM\JoinColumn(name =company,referencedColumnName =id,nullable = false)
* /
protected $ company ;

/ **
* @var对象BizTV \MediaManagementBundle\Entity\Folder
*
* @ ORM\ManyToOne(targetEntity =BizTV \\ \\ M MediaManagementBundle\Entity\Folder)
* @ ORM\JoinColumn(name =folder,referencedColumnName =id,nullable = true)
* /
protected $ folder ;


/ **
* @ Assert\File(maxSize =6000000)
* /
public $ file;


/ **
* @ ORM\PrePersist()
* @ ORM\PreUpdate()
* /
public函数preUpload()
{
if(null!== $ this-> file){
// do whatever you want to generate a unique name
$ this-> ; path = sha1(uniqid(mt_rand(),true))。'。'$ this-> file-> guessExtension();
}
}

/ **
* @ ORM\PostPersist()
* @ ORM\PostUpdate()
* /
public function upload()
{
if(null === $ this-> file){
return;
}

//如果移动文件时出现错误,则会由move()自动抛出异常
//。这将正确地阻止
//实体在错误
$ this-> file-> move($ this-> getUploadRootDir(),$ this-> path );

unset($ this-> file);
}

/ **
* @ ORM\PostRemove()
* /
public function removeUpload()
{
if($ file = $ this-> getAbsolutePath()){
unlink($ file);
}
}

public function getAbsolutePath()
{
return null === $ this-> path? null:$ this-> getUploadRootDir()。'/'。$ this-> path;
}

public function getWebPath()
{
return null === $ this-> path? null:$ this-> getUploadDir()。'/'。$ this-> path;
}

保护函数getUploadRootDir()
{
//上传文档应保存的绝对目录路径
返回__DIR __。 /../../../幅/'.$这 - > getUploadDir();

}

保护功能getUploadDir()
{
//摆脱__DIR__,所以当显示上传的文档/图像时不拧螺丝在视图中。
return'uploads / images';
}


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

/ **
*设置名称
*
* @param string $ name
* /
public function setName($ name)
{
$ this-> name = $ name;
}

/ **
*获取名称
*
* @return string
* /
public function getName )
{
return $ this-> name;
}

/ **
*设置宽度
*
* @param integer $ width
* /
public function setWidth($ width)
{
$ this-> width = $ width;
}

/ **
*获取宽度
*
* @return integer
* /
public function getWidth )
{
return $ this-> width;
}

/ **
*设置高度
*
* @param integer $ height
* /
public function setHeight($ height)
{
$ this-> height = $ height;
}

/ **
*获取高度
*
* @return integer
* /
public function getHeight )
{
return $ this-> height;
}

/ **
*设置路径
*
* @param string $ path
* /
public function setPath($ path)
{
$ this-> path = $ path;
}

/ **
*获取路径
*
* @return string
* /
public function getPath )
{
return $ this-> path;
}

/ **
*设置公司
*
* @param BizTV\BackendBundle\Entity\company $ company
* /
public function setCompany(\BizTV\BackendBundle\Entity\company $ company)
{
$ this-> company = $ company;
}

/ **
*获取公司
*
* @return BizTV\BackendBundle\Entity\company
* /
public function getCompany()
{
return $ this-> company;
}

/ **
*设置文件夹
*
* @param BizTV\MediaManagementBundle\Entity\Folder $ folder
* /
public function setFolder(\BizTV\MediaManagementBundle\Entity\Folder $ folder = NULL)
{
$ this-> folder = $ folder;
}

/ **
*获取文件夹
*
* @return BizTV\MediaManagementBundle\Entity\Folder
* /
public function getFolder()
{
return $ this-> folder;
}


}

 <?php 

命名空间BizTV\MediaManagementBundle\Form;

使用Symfony\Component\Form\AbstractType;
使用Symfony\Component\Form\FormBuilder;

class ImageType extends AbstractType
{
function __construct($ createAction = 0){
$ this-> createAction = $ createAction;
}

public function buildForm(FormBuilder $ builder,array $ options)
{

$ createAction = $ this-> createAction;

if($ createAction){
$ builder
- > add('file')
;
}

$ builder
- > add('name','text',array('label'=>'Namn'))
;
}

public function getName()
{
return'biztv_mediamanagementbundle_imagetype';
}
}


解决方案

你为了安全起见,不能为上传字段设置文件。看到这里了解更多信息。 如何设置HTML文件字段的值?


I am using a standard implementation of file upload in connection with doctrine, as per the example on the symfony2 website tutorials.

When my upload form encounters an error in validation, and sends the user back to the form with error messages, it looses the file chosen for upload, although if I var_dump my $entity->file I can see that it has the file...

    //if form is valid, do some stuff... if not:
    else {

        //var_dump($entity->file); //This works, I get my file
        //die;

        //Get and check the folder chosen as parent
        $entity->setFolder( $this->checkFolderId($request->request->get('folder')) ); //will cause die() if folder doesn't belong to this company

        $folders = $this->getFolders();

        return $this->render('BizTVMediaManagementBundle:Image:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
            'folders' => $folders,
            'fileExists' => $fileExists,
        ));

    }

After this is put to the twig view, there is nothing in the file field.

Here is my entity...

<?php

namespace BizTV\MediaManagementBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * BizTV\MediaManagementBundle\Entity\Image
 *
 * @ORM\Table(name="image")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class Image
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $name

     *
     * @ORM\Column(name="name", type="string", length=255)
     * @Assert\NotBlank
     */
    private $name;

    /**
     * @var integer $width
     *
     * @ORM\Column(name="width", type="integer")
     */
    private $width;

    /**
     * @var integer $height
     *
     * @ORM\Column(name="height", type="integer")
     */
    private $height;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $path;

    /**
    * @var object BizTV\BackendBundle\Entity\company
    *  
    * @ORM\ManyToOne(targetEntity="BizTV\BackendBundle\Entity\company")
    * @ORM\JoinColumn(name="company", referencedColumnName="id", nullable=false)
    */
    protected $company;     

    /**
    * @var object BizTV\MediaManagementBundle\Entity\Folder
    *  
    * @ORM\ManyToOne(targetEntity="BizTV\MediaManagementBundle\Entity\Folder")
    * @ORM\JoinColumn(name="folder", referencedColumnName="id", nullable=true)
    */
    protected $folder;


    /**
     * @Assert\File(maxSize="6000000")
     */
     public $file;


    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->file) {
            // do whatever you want to generate a unique name
            $this->path = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if (null === $this->file) {
            return;
        }

        // if there is an error when moving the file, an exception will
        // be automatically thrown by move(). This will properly prevent
        // the entity from being persisted to the database on error
        $this->file->move($this->getUploadRootDir(), $this->path);

        unset($this->file);
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        if ($file = $this->getAbsolutePath()) {
            unlink($file);
        }
    }    

    public function getAbsolutePath()
    {
        return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
    }

    public function getWebPath()
    {
        return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
    }

    protected function getUploadRootDir()
    {
        // the absolute directory path where uploaded documents should be saved
        return __DIR__.'/../../../../web/'.$this->getUploadDir();

    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view.
        return 'uploads/images';
    }


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

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

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

    /**
     * Set width
     *
     * @param integer $width
     */
    public function setWidth($width)
    {
        $this->width = $width;
    }

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

    /**
     * Set height
     *
     * @param integer $height
     */
    public function setHeight($height)
    {
        $this->height = $height;
    }

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

    /**
     * Set path
     *
     * @param string $path
     */
    public function setPath($path)
    {
        $this->path = $path;
    }

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

    /**
     * Set company
     *
     * @param BizTV\BackendBundle\Entity\company $company
     */
    public function setCompany(\BizTV\BackendBundle\Entity\company $company)
    {
        $this->company = $company;
    }

    /**
     * Get company
     *
     * @return BizTV\BackendBundle\Entity\company 
     */
    public function getCompany()
    {
        return $this->company;
    }

    /**
     * Set folder
     *
     * @param BizTV\MediaManagementBundle\Entity\Folder $folder
     */
    public function setFolder(\BizTV\MediaManagementBundle\Entity\Folder $folder = NULL)
    {
        $this->folder = $folder;
    }

    /**
     * Get folder
     *
     * @return BizTV\MediaManagementBundle\Entity\Folder 
     */
    public function getFolder()
    {
        return $this->folder;
    }


}

And the form:

<?php

namespace BizTV\MediaManagementBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class ImageType extends AbstractType
{
    function __construct($createAction=0) {
        $this->createAction = $createAction;    
    }   

    public function buildForm(FormBuilder $builder, array $options)
    {

        $createAction = $this->createAction;

        if ($createAction) {        
            $builder
                ->add('file')
            ;
        }

        $builder
            ->add('name', 'text', array('label' => 'Namn'))
        ;
    }

    public function getName()
    {
        return 'biztv_mediamanagementbundle_imagetype';
    }
}

解决方案

You can't, for security purposes, set a file for the upload field. See here for more info. How to set the value of a HTML file field?

这篇关于symfony2文件在表单错误时丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆