我正在使用 symfony 2.8 版本,我遇到了以下问题。我希望实体“文章”的字段“seeAlso”被限制为具有零(无)或至少 3 个对象(另一篇文章)。所以我在我的 yaml 验证中有这些:
seeAlso:
- Count:
min: 3
minMessage: 'you have got to pick zero or at least three articles'
它检查它是否小于三个井,但它不允许我让该字段为空。我该如何进行这项工作?
我正在使用 symfony 2.8 版本,我遇到了以下问题。我希望实体“文章”的字段“seeAlso”被限制为具有零(无)或至少 3 个对象(另一篇文章)。所以我在我的 yaml 验证中有这些:
seeAlso:
- Count:
min: 3
minMessage: 'you have got to pick zero or at least three articles'
它检查它是否小于三个井,但它不允许我让该字段为空。我该如何进行这项工作?
您应该定义一个自定义验证。您可以通过两种方式进行
首先你需要创建一个约束类
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class ConstraintZeroOrAtLeastThreeConstraint extends Constraint
{
public $message = 'Put here a validation error message';
public function validatedBy()
{
return get_class($this).'Validator';
}
}
在这里,您已经定义了一个带有消息的约束,并且您告诉 symfony 哪个是验证器(我们将在下面定义)
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ZeroOrAtLeastThreeConstraintValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!count($value)) {
return;
}
if (count($value) >= 3) {
return;
}
$this
->context
->buildValidation('You should choose zero or at least three elements')
->addViolation();
}
}
现在您可以通过使用注释来在属性上使用您的验证器@ ConstraintZeroOrAtLeastThreeConstraint
(当然,您必须在实体文件中导入才能使用)
当然,您甚至可以自定义值 0 和 3 以将此约束概括为ZeroOrAtLeastTimesConstraint
使用
public function __construct($options)
{
if (!isset($options['atLeastTimes'])) {
throw new MissingOptionException(...);
}
$this->atLeastTimes = $options['atLeastTimes'];
}
/**
* @Assert\Callback
*/
public function validate(ExecutionContextInterface $context, $payload)
{
if (!count($this->getArticles()) {
return;
}
if (count($this->getArticles() >= 3) {
return;
}
$context
->buildViolation('You should choose 0 or at least 3 articles')
->addViolation();
}