我有一个表单,我在我的类ItemType中创建:
class ItemType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class,
array(
'constraints' => array(
)
)
)
->add('shortname', TextType::class,
array(
'constraints' => array(
)
)
)
->add('somethingelse', TextType::class,
array(
'constraints' => array(
new NotBlank()
)
)
)
;
}
public function getBlockPrefix()
{
return 'item';
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bundle\Entity\Item',
'csrf_protection' => false,
'allow_extra_fields' => true
));
}
}
现在我要做的是编写一个自定义约束,确保填充名称或短名称。我怎样才能做到这一点?这是一个应该在表格而不是在一个领域的约束......对吗?或者我使用validation_groups?如果是这样 - 如何向validation_group添加约束?
提前致谢
答案 0 :(得分:0)
callback constraint可用于实现更复杂的验证规则:
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bundle\Entity\Item',
'csrf_protection' => false,
'allow_extra_fields' => true,
'constraints' => [
new Assert\Callback(['callback' => function (ExecutionContextInterface $context) {
$object = $context->getObject();
if (null === $object->getName() && null === $object->getShortname()) {
$context->buildViolation('Either name or short name must be specified')->addViolation();
}
}]),
],
));
}