我是一个 Symfony 菜鸟,试图想象如何最好地基于它或不同的字段来验证表单字段,但没有成功。案例:表格将要求提供出生日期或年龄。如果输入了 dob,则忽略年龄。如果输入年龄并且 dob 为空,则表示 dob 是今天的日期减去年龄的年数。如果两者都没有输入,则会引发验证错误。我已经通过 Smarty 验证实现了这一点;作为一项学习练习,我试图在 Symfony 中重现该应用程序。
我看过这个解决方案,其中两个字段都是实体的属性。在我的情况下,年龄不是,只有 dob。所以我不清楚如何应用该解决方案。我非常感谢指点。
谢谢。
George PS:(已编辑:dreck 已删除) PPS:(已编辑:已删除以为几乎可以工作的版本腾出空间)表格:
// src\Mana\AdminBundle\Resources\views\Form\Type\NewClientType.php
namespace Mana\AdminBundle\Form\Type;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Mana\AdminBundle\Validator\Constraints;
class NewClientType extends AbstractType {
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array('validation_groups' => 'client_new',
'validation_constraint' => new DOBorAge(),
));
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('fname', null, array('required' => false));
$builder->add('sname', null, array('required' => false));
$builder->add('dob', 'birthday', array('widget' => 'single_text', 'required' => false));
$builder->add('age', null, array('mapped' => false, 'required' => false));
}
public function getName() {
return 'client_new';
}
}
服务:
services:
client_new:
class: Mana\AdminBundle\Validator\Constraints\DOBorAgeValidator
scope: request
tags:
- { name: validator.constraint_validator, alias: dobage_validator}
验证器:
// src\Mana\AdminBundle\Form\Type\DOBorAge.php
namespace Mana\AdminBundle\Form\Type;
use Mana\AdminBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
class DOBorAge extends Constraint {
public $message = 'Either a date of birth or age must be present';
public function validatedBy() {
return 'dobage_validator';
}
public function getTargets() {
return Constraint::CLASS_CONSTRAINT;
}
}
和
// src\Mana\AdminBundle\Validator\Constraints\DOBorAgeValidator.php
namespace Mana\AdminBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class DOBorAgeValidator extends ConstraintValidator {
protected $request;
public function __construct(Request $request) {
$this->request = $request;
}
public function validate($value, Constraint $constraint) {
var_dump($this->request->request->get('client'));
die();
return true;
}
}