2013-05-25 1 views
7

Я использую стандартную реализацию загрузки файлов в связи с доктриной, как в примере на обучающих веб-сайтах symfony2.Файл symfony2, потерянный при ошибке формы

Когда моя форма загрузки встречает ошибку в проверке и отправляет пользователя обратно в форму с сообщениями об ошибке, она теряет файл, выбранный для загрузки, хотя если я var_dump мой файл $ entity->, я вижу, что он имеет файл ...

//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, 
     )); 

    } 

После того, как это помещено в представление твика, в поле файла ничего нет.

Вот моя сущность ...

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


} 

И форма:

<?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'; 
    } 
} 
+0

Пожалуйста, предоставьте информацию о том, как вы пытаетесь вывести свой файл в веточке. – nifr

+0

Можете ли вы решить проблему с моим ответом? webPath - это свойство, содержащее путь к изображению после загрузки. если какие-либо вопросы оставили комментарий в противном случае, согласитесь с pleae :) – nifr

+0

Я не выводил его сам, я просматриваю свою форму после того, как она не прошла проверку, так что пользователь может исправить недостающие поля, и если бы файл был выбран, я ожидал бы его все еще существуют вместе с другими значениями, которые были правильными, оставляя пустые поля только для тех атрибутов, которые не удалось проверить. –

ответ

5

Вы не можете, в целях безопасности, установить файл для поля загрузки. См. Здесь для получения дополнительной информации. How to set the value of a HTML file field?

0

Я предлагаю вам пытаются получить доступ к файла свойство вашей сущности в веточке. Пожалуйста, быстро просмотрите свою функцию загрузки.

/** 
* @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); 
} 

Как вы видите, свойство файла отключается после завершения операции загрузки и сохранения.

Теперь, чтобы показать свою фактическую картинку, вы должны использовать свойство web-сайта , так как это сгенерированный URL-адрес для вашего недавно загруженного изображения.

Загрузка файлов с помощью Dustin10/VichUploaderBundle может быть проще, если вы также можете использовать абстракцию файловой системы с помощью KnpLabs/Gaufrette.

Надеется, что это помогает :)

+0

В строке 4 моего первого примера кода я все еще могу получить доступ к моему файлу, так что он все еще там когда контроллер переходит к просмотру представления. Я просто создаю форму вида из моего объекта формы (imageType, как код, включенный в вопрос).Поэтому, если пользователь забывает указать файл, выбранная папка «остается» в форме после возврата к форме для cmplting с именем, но выбранного изображения там нет. –

Смежные вопросы