2012-08-28 45 views
9

我想使用文件驗證器來限制文件輸入的MIME類型。不幸的是,這個約束從來沒有使用過,所有的文件都被接受爲什麼Symfony文件驗證器不起作用

namespace WNC\SoldierBundle\Entity; 

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

/** 
* WNC\SoldierBundle\Entity\Soldier 
* 
* @ORM\Table(name="soldier") 
* @ORM\Entity(repositoryClass="WNC\SoldierBundle\Entity\SoldierRepository") 
* @ORM\HasLifecycleCallbacks() 
*/ 
class Soldier 
{ 

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

    /** 
    * @var string $file 
    * 
    * @Assert\Image() 
    * @Assert\NotBlank() 
    */ 
    public $file; 


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

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

    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/pictures'; 
    } 

    /** 
    * @ORM\PrePersist() 
    * @ORM\PreUpdate() 
    */ 
    public function preUpload() 
    { 

     if($this->picture && file_exists($this->getAbsolutePath())) { 
      unlink($this->getAbsolutePath()); 
     } 

     if (null !== $this->file) { 
      // do whatever you want to generate a unique name 
      $this->picture = uniqid().'.'.$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->picture); 

    } 

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

表單生成器:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('mothers_name') 
     ->add('service_end_date', 'date',array(
      'widget' => 'single_text', 
      'format' => 'MM/dd/yyyy', 
      'attr' => array('class' => 'date six columns') 
     )) 
     ->add('army_unit') 
     ->add('city', 'city_selector') 
     ->add('gender', 'choice', array(
      'choices' => array(0 => 'Male', 1 => 'Female'), 
      'required' => false, 
      'expanded' => true, 
      'label' => 'Male/Female', 
      'data' => 0 
     )) 
     ->add('file','file', array(
      'data_class' => 'Symfony\Component\HttpFoundation\File\File', 
      'label' => 'Picture' 
     )) 
     ->add('self_description', 'textarea') 
     ->add('video', null, array(
      'attr' => array(
      'placeholder' => 'some link here' 
     ))) 
     ->add('wants_to_contact', null, array(
      'label' => Soldier::getLabel('wants_to_contact') 
     )) 
     ->add('comments', 'textarea') 
     ->add('user', new NameFormType('Application\Sonata\UserBundle\Entity\User')) 
     ->add('city', 'city_selector') 

    ; 


} 

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    $resolver->setDefaults(array(
     'validation_groups' => array('Registration'), 
     'cascade_validation' => true, 
    )); 


} 

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

控制器:

/** 
* Creates a new Soldier entity. 
* 
* @Route("/create", name="soldier_create") 
* @Method("POST") 
* @Template("WNCSoldierBundle:Soldier:new.html.twig") 
*/ 
public function createAction(Request $request) 
{ 
    $entity = new Soldier(); 
    $form = $this->createForm(new SoldierType(), $entity); 
    $form->bind($request); 

    if ($form->isValid()) { 
     $em = $this->getDoctrine()->getManager(); 

     $em->persist($entity); 
     $em->flush(); 

     return $this->redirect($this->generateUrl('soldier_show', array('id' => $entity->getId()))); 
    } 

    return array(
     'entity' => $entity, 
     'form' => $form->createView(), 
    ); 
} 
+0

不同的主題:我已經注意到你有與路徑相同的問題,你可能想檢查一下:http://stackoverflow.com/questions/12168086/how-to-deal-with-relative-paths -in-symfony-2 – ChocoDeveloper

+0

謝謝,但保存工作無懈可擊,但我無法找到驗證無效的原因。也許是因爲它只是一個虛擬的字段沒有用作db列? –

+0

我剛剛創建了一個使用此斷言的測試應用程序,它工作正常。非圖像出現錯誤,圖像通過。這是在Symfony2.1上。你的表單構建器是什麼樣的? – Kris

回答

3

我找到了解決方案。在表單定義我使用`'validation_groups'=>數組('註冊')。我認爲,當沒有驗證者組時,它將與表單定義中的任何一個匹配。

當我已經添加組屬性驗證器一切都最後工作。因此,使用validation.yml例如:

WNC\SoldierBundle\Entity\Soldier: 
    properties: 
     file: 
      - Image: {groups: [Registration]} 
5

退房此之前的SO問題:Symfony2 validation using Assert annotation does not work。您可能需要確保符合所有推薦的配置以使用Symfony2。

另外,不需要驗證$pictureImage約束,因爲它不是文件/圖像。

/** 
* @var string $picture 
* @Assert\Image()          <-- Should be removed 
* @ORM\Column(name="picture", type="string", length=255) 
*/ 
private $picture; 

/** 
* @var string $file          <-- @var UploadedFile $file 
* 
* @Assert\Image() 
* @Assert\NotBlank() 
*/ 
public $file; 

實際上,我是能夠驗證上傳的文件是使用YAML替代,所以你可能也想嘗試一個形象,如果沒有出現。

+0

感謝您的回答,不幸的是您的建議並未解決問題。您提供的鏈接與我使用的其他驗證程序相關。我沒有像標準的驗證器,如要求,非空等問題,我檢查了VichUploaderBundle和刪除生命週期註釋,但它沒有作出改變。你使用什麼symfony版本? –

+0

另一方面,yml驗證文件在這種情況下也是無效的 –

+0

Hi @LukeAdamczewski,是的,我知道我提供的鏈接是關於不同的驗證器。我認爲是有用的,雖然實際上是這個答案http://stackoverflow.com/a/7946408/1349295關於國際擴展。也許確保符合sf2的所有推薦配置?順便說一句,我在sf2.0上工作。我已經將一些代碼從2.1移植到2.0,並且遇到了一些重大變化(並且仍在變化中)。順便說一下,sf2.1不再處於測試階段!剛剛檢查過。也許嘗試升級到最新的發行版。 :) –

0

您可以使用約束這是不適合你的領域。只需在$ file屬性上使用File約束即可。

相關問題