我有表格女巫使用自定义非映射子表单。
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('subtype', 'my-subtype');
}
}
子表单由多个字段组成,我需要对它们进行额外的检查。 Callback约束非常适合这项工作。但是我找不到如何在子窗体上添加这个约束的方法。
到目前为止,我已尝试在setDefaultOptions()中设置Callback,或者在buildForm()中使用setAttribute()设置它,但不会对回调进行评估。
目前我只是将Callback添加到其中一个字段:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('field1', 'text')
->add(
'field2', 'text',
array(
'constraints' => array(
new Callback(array(
'methods' => array(array($this, 'validateMyType'))
))
)
));
}
public function validateMyType($data, ExecutionContextInterface $context) {
// Validation failed...
$context->addViolationAt('subtype', "mySubtypeViolation");
return;
}
然而,这阻止我在整个子类型上添加违规。我在addViolationAt()中使用的内容总是将违规添加到托管Callback约束的字段中。
答案 0 :(得分:1)
我很惊讶你不能在setDefaultOptions()中添加Callback,因为我刚测试了这个并且这个有效。这绝对是我一开始就会这么做的。
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'constraints' => new Callback([$this, 'test'])
]);
}
public function test($data, ExecutionContextInterface $context)
{
return;
}
执行test
方法(我使用调试器检查)。
答案 1 :(得分:0)
首先我在配置中输入了拼写错误,因此没有触发回调方法。其次,error-bubbling被自动设置,因此错误被添加到整个表单中。所以我只需要手动禁用它。
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults([
'error_bubbling' => false, // Automatically set to true for compound forms.
'constraints' =>
array(
new Callback(array(
'methods' => array(array($this, 'validateMyType'))
))
)]);
}
比任何其他回调更多地添加违规行为:
public function validateFacrMembership($data, ExecutionContextInterface $context) {
$context->addViolation("invalidValueMessage");
}