2015-05-31 4 views
2

У меня проблема с form validation в symfony2.Файл не найден во время использования LifecycleCallbacks

В моем случае $form->isValid() результатов команды в The file could not be found. несмотря на то, что я обеспечиваю файл во время заполнения формы

Кроме отладке из setFile функции в documents entity приводит к выводу, что значение файла установлено правильно. Функция SetFile и результаты print_r представлены ниже:

/** 
* Sets file. 
* 
* @param UploadedFile $file 
*/ 
public function setFile(UploadedFile $file = null) 
{ 
    $this->file = $file; 
    print_r($this->file); // [THIS IS FOR TEST] 
    // check if we have an old image path 
    if (is_file($this->getAbsolutePath())) { 
     // store the old name to delete after the update 
     $this->temp = $this->getAbsolutePath(); 
    } else { 
     $this->link = 'initial'; 
    } 
} 

print_r результат:

Symfony\Component\HttpFoundation\File\UploadedFile Object ([test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => firefox.exe [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => application/octet-stream [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 338032 [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0 [pathName:SplFileInfo:private] => C:\wamp\tmp\php9DC3.tmp [fileName:SplFileInfo:private] => php9DC3.tmp) 

Мои вопросы поэтому даже если файл предоставляется правильно форма валидатор не удается?

Когда я комментирую часть своей функции setFile(), она начинает работать, что приводит к исключению перемещения.

'

/** 
* Sets file. 
* 
* @param UploadedFile $file 
*/ 
public function setFile(UploadedFile $file = null) 
{ 
    $this->file = $file; 

    /*if (is_file($this->getAbsolutePath())) { 
     // store the old name to delete after the update 
     $this->temp = $this->getAbsolutePath(); 
    } else { 
     $this->link = 'initial'; 
    }*/ 
} 

Мой класс формы:

<?php 

namespace AppBundle\Form; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolverInterface; 

class DocumentsType extends AbstractType 
{ 
    /** 
    * @param FormBuilderInterface $builder 
    * @param array $options 
    */ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('marker') 
      ->add('document_date', 'date', array('widget' => 'single_text', 'format' => 'yyyy-MM-dd')) 
      ->add('file', 'file') 
      ->add('notes', 'text', array('required' => "false")) 
     ; 
    } 

Мой контроллер, в котором is_valid функция приводит к отрицательному результату:

 /** 
    * This code is aimed at checking if the book is choseen and therefore whether any further works may be carried out 
    */ 
    $session = new Session(); 
    if(!$session->get("App_Books_Chosen_Lp")) return new RedirectResponse($this->generateUrl('app_listbooks')); 
    // Authorization goes here 

    $documents = new Documents(); 
    $form = $this->createForm(new DocumentsType(), $documents); 
    $form->add('save', 'submit', array('label' => 'Dodaj dokument')); 
    $form->handleRequest($request); 

    if ($form->isValid()) { 

Мои документы Класс:

<?php 
namespace AppBundle\Entity; 
use Doctrine\ORM\Mapping as ORM; 
use Symfony\Component\Validator\Constraints as Assert; 
use Symfony\Component\HttpFoundation\File\UploadedFile; 

/** 
* @ORM\Entity 
    * @ORM\HasLifecycleCallbacks 
* @ORM\Table(name="Documents") 
*/ 

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

    /** 
    * @ORM\ManyToOne(targetEntity="Books", inversedBy="documents") 
    * @ORM\JoinColumn(name="book_id", referencedColumnName="id") 
    */ 
    protected $book; 

    /** 
    * @ORM\Column(type="string", length=220) 
    */ 
    protected $marker; 

    /** 
    * @ORM\Column(type="date", length=220) 
    */ 
    protected $document_date; 

    /** 
    * @ORM\Column(type="string", length=220) 
    * @Assert\File(maxSize="6000000") 
    */ 
    protected $link; 

    /** 
    * @ORM\Column(type="text") 
    */ 
    protected $notes; 


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

    /** 
    * Set marker 
    * 
    * @param string $marker 
    * @return Documents 
    */ 
    public function setMarker($marker) 
    { 
     $this->marker = $marker; 

     return $this; 
    } 

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

    /** 
    * Set document_date 
    * 
    * @param \DateTime $documentDate 
    * @return Documents 
    */ 
    public function setDocumentDate($documentDate) 
    { 
     $this->document_date = $documentDate; 

     return $this; 
    } 

    /** 
    * Get document_date 
    * 
    * @return \DateTime 
    */ 
    public function getDocumentDate() 
    { 
     return $this->document_date; 
    } 

    /** 
    * Set link 
    * 
    * @param string $link 
    * @return Documents 
    */ 
    public function setLink($link) 
    { 
     $this->link = $link; 

     return $this; 
    } 

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


    /** 
    * Set notes 
    * 
    * @param string $notes 
    * @return Documents 
    */ 
    public function setNotes($notes) 
    { 
     $this->notes = $notes; 

     return $this; 
    } 

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

    /** 
    * Set book 
    * 
    * @param \AppBundle\Entity\Books $book 
    * @return Documents 
    */ 
    public function setBook(\AppBundle\Entity\Books $book = null) 
    { 
     $this->book = $book; 

     return $this; 
    } 

    /** 
    * Get book 
    * 
    * @return \AppBundle\Entity\Books 
    */ 
    public function getBook() 
    { 
     return $this->book; 
    } 

    /* 
    * ### FILE UPLOAD PROCESS ### 
    */ 

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

    /** 
    * Stores temporay path 
    */ 
    private $temp; 

    /** 
    * Sets file. 
    * 
    * @param UploadedFile $file 
    */ 
    public function setFile(UploadedFile $file = null) 
    { 
     $this->file = $file; 
     print_r($this->file); // [THIS IS FOR TEST] 
     // check if we have an old image path 
     if (is_file($this->getAbsolutePath())) { 
      // store the old name to delete after the update 
      $this->temp = $this->getAbsolutePath(); 
     } else { 
      $this->link = 'initial'; 
     } 
    } 

    /** 
    * @ORM\PrePersist() 
    * @ORM\PreUpdate() 
    */ 
    public function preUpload() 
    { 
     if (null !== $this->getFile()) { 
      $this->link = $this->getFile()->guessExtension(); 
     } 
    } 

    /** 
    * Get file. 
    * 
    * @return UploadedFile 
    */ 
    public function getFile() 
    { 
     return $this->file; 
    } 

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

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

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

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

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

     // check if we have an old image 
     if (isset($this->temp)) { 
      // delete the old image 
      unlink($this->temp); 
      // clear the temp image path 
      $this->temp = null; 
     } 

     // you must throw an exception here if the file cannot be moved 
     // so that the entity is not persisted to the database 
     // which the UploadedFile move() method does 
     $this->getFile()->move(
      $this->getUploadRootDir(), 
      $this->id.'.'.$this->getFile()->guessExtension() 
     ); 

     $this->setFile(null); 
    } 


    /** 
    * @ORM\PreRemove() 
    */ 
    public function storeFilenameForRemove() 
    { 
     $this->temp = $this->getAbsolutePath(); 
    } 

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

} 

ответ

1

Я выяснил, в чем проблема. Я пометил столбец «ссылка» в качестве файла и, следовательно, валидатор потерпел неудачу, поскольку ссылка была текстовой, а не файлом.

Мой код ссылки был:

/** 
* @ORM\Column(type="string", length=220) 
* @Assert\File(maxSize="6000000") 
*/ 
protected $link; 

и линия:

* @Assert\File(maxSize="6000000") 

там быть не должно.

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