使用True或Callback验证断言,这里有一个示例来检查用户是否必须提供至少一个文件夹:
<?php
namespace Acme\BlogBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Image
{
// ...properties, functions, etc...
/**
* @Assert\True(message = "You must give at least an existing folder or a new folder")
*/
public function isThereOneFieldFilled()
{
return ($this->existingfolder || $this->folder); // If false, display an error !
}
}
这是另一个示例,如果用户必须只提供一个字段而不是两个字段:
/**
* @Assert\True(message = "You must give an existing folder or a new folder, not both")
*/
public function isThereOnlyOneFieldFilled()
{
return (!$this->existingfolder && $this->folder || $this->existingfolder && !$this->folder);
}
编辑:
表单内的回调验证(我在这里找到了一个示例):
// use ...
use Symfony\Component\Form\CallbackValidator;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
// Inside the form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('existingfolder', 'entity', array(
'class' => 'ImageBundle:Folder',
'required' => false,
))
->add('folder', 'text', array('required' => false))
->add('file', 'file');
// Use the CallbackValidator like a TrueValidator behavior
$builder->addValidator(new CallbackValidator(function(FormInterface $form) {
if (!$form["existingfolder"]->getData() && !$form["folder"]->getData()) {
$form->addError(new FormError('You must give at least an existing folder or a new folder'));
}
}));
}