Symfony 没有为约束配置默认选项
我正在按照symfony 2的文档编写自己的约束(愚蠢的简单)。但在运行之后,我出现了以下错误:Symfony 没有为约束配置默认选项,symfony,Symfony,我正在按照symfony 2的文档编写自己的约束(愚蠢的简单)。但在运行之后,我出现了以下错误: No default option is configured for constraint Cgboard\SignupBundle\Validator\Constraints\PasswordNotMatching 我在stackoverflow的另一篇文章中看到了一个使用服务的解决方案,但我不确定该解决方案是否是最好的,在文档中没有出现任何关于这个简单示例的服务 通过调试,我终于看到buil
No default option is configured for constraint Cgboard\SignupBundle\Validator\Constraints\PasswordNotMatching
我在stackoverflow的另一篇文章中看到了一个使用服务的解决方案,但我不确定该解决方案是否是最好的,在文档中没有出现任何关于这个简单示例的服务
通过调试,我终于看到buildform()方法从未被调用。为什么?
我的确认码
Cgboard\SignupBundle\Entity\SignupData:
properties:
email:
- NotBlank: ~
nickname:
- NotBlank: ~
password:
- NotBlank: ~
password_repeat:
- NotBlank: ~
- Cgboard\SignupBundle\Validator\Constraints\PasswordNotMatching: ~;
我的验证器:
<?php
namespace Cgboard\SignupBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class PasswordNotMatchingValidator extends ConstraintValidator
{
public function validate($DataForm, Constraint $constraint)
{
return false;
}
}
你应该使用~
而不是~代码>在您的验证.yml
中:
Cgboard\SignupBundle\Entity\SignupData:
properties:
email:
- NotBlank: ~
nickname:
- NotBlank: ~
password:
- NotBlank: ~
password_repeat:
- NotBlank: ~
- Cgboard\SignupBundle\Validator\Constraints\PasswordNotMatching: ~
解释
Cgboard\SignupBundle\Validator\Constraints\PasswordNotMatching:~
的意思不同于…:~
。~
运算符在Yaml中表示null
。执行:~
时,您可以将其配置为null
(无)。但是在做~
您可以使用字符串“~;”
对其进行配置
有两种方法可以配置约束的选项:使用数组:
Choice:
choices: [red, blue]
但有些约束有一个“默认选项”。对于选择约束,choices
是默认选项。这意味着可以按如下方式进行上述操作:
Choice: [red, blue]
现在,[红色,蓝色]
将被设置为选项
在本例中,您定义了值“~;”
。因为这不是null
,所以它尝试将其设置为默认选项。但是约束没有配置默认选项,因此Symfony失败。当使用~
时,它是null
,Symfony不会设置任何选项。对于看到此线程并使用XML而不是YAML的任何人,这也可能是相同错误消息的可能解决方案:
这是行不通的:
<getter property="fieldname">
<constraint name="Test\TestBundle\Validator\Constraints\Test">
</constraint>
</getter>
但这将起作用:
<getter property="fieldname">
<constraint name="Test\TestBundle\Validator\Constraints\Test" />
</getter>
services.yml中添加了约束类而不是验证器类,因此出现了此错误。Symfony2找不到验证器所需的方法。
Choice: [red, blue]
<getter property="fieldname">
<constraint name="Test\TestBundle\Validator\Constraints\Test">
</constraint>
</getter>
<getter property="fieldname">
<constraint name="Test\TestBundle\Validator\Constraints\Test" />
</getter>