8

我想使用文件验证器来限制文件输入的 mime 类型。不幸的是,这个约束从未使用过,所有文件都被接受了。

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(),
    );
}
4

3 回答 3

4

查看之前的 SO 问题:Symfony2 validation using Assert annotation does not work。你可能想确保你已经满足了使用 Symfony2 的所有推荐配置。

此外,没有必要$picture使用Image约束进行验证,因为它不是文件/图像。

/**
 * @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 替代方法验证上传的文件是否为图像,因此如果没有任何结果,您可能还想尝试一下。

于 2012-09-04T11:49:21.900 回答
2

我找到了解决方案。在表单定义中,我使用''validation_groups' => array('Registration')。我认为当没有验证器组时,它将与表单定义中的任何一个匹配。

当我将 groups 属性添加到验证器时,一切终于开始工作了。因此,例如使用validation.yml

WNC\SoldierBundle\Entity\Soldier:
    properties:
        file:
            - Image: {groups: [Registration]}
于 2012-09-10T11:30:06.607 回答
0

您使用不适合您的领域的约束。只需对 $file 属性使用 File 约束即可。

于 2015-05-24T15:24:00.613 回答