Symfony2 表单中的非空白文件输入字段 [英] Non blank file input field in Symfony2 form
问题描述
在我的 Doctrine 实体中,我的表单的 data_class
有一个文件属性,定义如下:
In my Doctrine entity, which is data_class
for my form I have a file property defined like this:
/**
* Image.
*
* @AssertNotBlank
* @AssertFile
* @AssertImage(minWidth="138", minHeight="96")
*/
protected $file;
另外,用 ->add('file', 'file')
...
创建实体完美无缺,但问题是当我使用表单更新此实体时.它再次请求文件,因为它有@AssertNotBlank.由于此表单中还有其他字段,因此我不想在每次更新时重新上传图片.
Creating entity works perfect, but the problem is when I use form to update this entity. It asks for file again, since it has @AssertNotBlank. Since I have other fields in this form, I don't want to reupload image on every update.
当我删除@AssertNotBlank 时,一切正常,但我希望这个文件字段是强制性的.
When I remove @AssertNotBlank, everithing works fine, but I want this file field to be mandatory.
有什么想法吗?
推荐答案
您有两种方法可以解决这种情况,并且都依赖于 Callback
验证器:(Symfony 回调)
You have two ways out this situation and both rely on Callback
validators: (Symfony callback)
或者将名为 isUpdate
的 boolean
添加到您的实体中,该实体不会被持久化,并且会告诉验证器尝试了哪个操作.这种方法在上面的链接中有完整的描述.
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.
解决此问题的另一种方法是直接将回调验证器添加到您的表单类型.同样,将需要一些 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屋!