Symfony2表单中的非空文件输入字段 [英] Non blank file input field in Symfony2 form

查看:75
本文介绍了Symfony2表单中的非空文件输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Doctrine实体中,我的表单是 data_class ,我有一个这样定义的文件属性:

In my Doctrine entity, which is data_class for my form I have a file property defined like this:

/**
     * Image.
     *
     * @Assert\NotBlank
     * @Assert\File
     * @Assert\Image(minWidth="138", minHeight="96")
     */
    protected $file;

此外,将其添加到 - > add('file ','file') ...

Also, added it to form type with ->add('file', 'file')...

创建实体完美,但问题是当我使用表单来更新此实体。它再次请求文件,因为它有@ Assert\NotBlank。因为我有这个表单的其他字段,我不想在每次更新时重新上传图像。

Creating entity works perfect, but the problem is when I use form to update this entity. It asks for file again, since it has @Assert\NotBlank. Since I have other fields in this form, I don't want to reupload image on every update.

当我删除@ Assert\NotBlank时,everithing工作正常,但我想要这个文件字段是必须的。

When I remove @Assert\NotBlank, everithing works fine, but I want this file field to be mandatory.

任何想法?

推荐答案

p>你有两种方法来解决这种情况,都依赖于回调验证器:( Symfony回调

You have two ways out this situation and both rely on Callback validators: (Symfony callback)

添加 boolean named isUpdate 给您的实体,不会被持久化,并会告诉验证器尝试哪个操作。这种方法在上面的链接中完全描述。

Either add boolean named isUpdate to you entity which will not be persisted and will tell validator which operation was attempted. This method is completely described in link above.

另一种解决方法是直接向Form类型添加回调验证器。再次,一些 isUpdate 标志将需要,但这次在Form类型(通过构造函数传递):

Another way to tackle this is to add Callback validator to your Form type directly. Again, some isUpdate flag will be needed but this time within Form type (pass it via constructor):

if ( $this->isUpdate == false ){
    $builder->addValidator(new CallbackValidator(function(FormInterface $form){
        if ( $form['image_file']->getData() == NULL ){
            $form->addError(new FormError('You need to specify image file.'));                  
        }
    }));
}

也许有更简单的方法来实现所需的验证,但是我来了这两个几个月后。

Maybe there is simplier way to achieve desired validation but I came upon these two few months back.

希望这有帮助...

这篇关于Symfony2表单中的非空文件输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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