我正在使用Symfony 2.8和FOSUser bundle 2.0进行用户管理。我正在尝试为电话号码字段创建自定义验证程序,但没有成功。
这是我的代码:
UserBundle / Resources / config / validation.xml
<class name="Acme\UserBundle\Entity\User">
<property name="phoneNumber">
<constraint name="Acme\UserBundle\Validator\Constraint\IsConfirmedPhonenumber">
<option name="groups">
<value>Acme</value>
</option>
</constraint>
</property>
</class>
服务定义
<service class="Acme\UserBundle\Validator\Constraint\IsConfirmedPhonenumberValidator" id="acme_user.validator.is_confirmed_phonenumber_validator">
<argument id="doctrine.orm.default_entity_manager" type="service"/>
<tag name="acme.constraint_phonenumber"/>
</service>
在我的表单上
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\UserBundle\Entity\User',
'intention' => 'profile',
));
}
我的自定义约束
class IsConfirmedPhonenumber extends Constraint
{
public $message = 'The phonenumber "%phonenumber%" is not verified.';
public function validatedBy()
{
return "acme.constraint_phonenumber";
}
}
和验证器
class IsConfirmedPhonenumberValidator extends ConstraintValidator
{
/**
* @var EntityManager
*/
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* Checks if the passed value is valid.
*
* @param mixed $value The value that should be validated
* @param Constraint $constraint The constraint for the validation
*/
public function validate($value, Constraint $constraint)
{
$phoneVerificationRepo = $this->em->getRepository('AcmeCoreBundle:PhoneVerification');
$phoneVerificationRepo->findBy(array('phoneNumber' => $value, 'verified' => true));
if(!$phoneVerificationRepo)
{
$this->context->buildViolation($constraint->message)
->setParameter('%phonenumber%', $value)
->addViolation();
}
return;
}
}
此配置对我不起作用,因为我的自定义验证程序中的validate方法永远不会被调用。
我设法通过在ProfileController的editAction方法的createForm工厂方法中指定验证组来解决此问题。
$form = $formFactory->createForm(['validation_groups' => array('AcmeProfile', 'Profile')]);
由于我要覆盖FOS工厂和ProfileController editAction,因此在config或自定义FormType中设置验证组也无济于事。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句