收集字段上的验证组

时间:2019-03-04 11:35:37

标签: php symfony symfony-forms symfony4

嗨,我收藏类型有问题

->add('attributes', CollectionType::class, [
    'entry_type' => CriteriaForm::class,
    'allow_add' => true,
    'required' => false,
    'constraints' => [
        new Valid(),
    ],
])

条件表看起来像这样

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('from', TextType::class, [
            'required' => false,
            'constraints' => [
                new Date([
                    'groups' => [
                        'date_type'
                    ]
                ]),
                new Type([
                    'type' => 'integer',
                    'groups' => [
                        'number_type'
                    ],
                ])
            ]
        ])
        ->add('to', TextType::class, [
            'required' => false,
            'constraints' => [
                new Date([
                    'groups' => [
                        'date_type'
                    ]
                ]),
                new Type([
                    'type' => 'integer',
                    'groups' => [
                        'number_type'
                    ],
                ])
            ]
        ])
        ->add('formType', TextType::class, [
            'constraints' => [
                new NotNull(),
                new NotBlank(),
            ]
        ])
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver
        ->setDefaults([
            'validation_groups' => function (FormInterface $form) {
                $data = $form->getData();

                if ($data['formType'] === 'date') {
                    return ['Default', 'date_type'];
                }

                return ['Default', 'number_type'];
            },
        ]);
}

并且validation_groups回调永远不会执行

编辑:

控制器

$form = $this->formFactory->create(SearchCriteriaForm::class);
$form->submit(json_decode($request->getContent(), true));

if (!$form->isValid()) {
    return new JsonResponse(null, Response::HTTP_BAD_REQUEST);
}

return new JsonResponse();

编辑2:“解决方案” 我也将datamapper选项设置为form,发现在验证之前数据已映射到对象,这就是问题所在。我从对象中获得了异常,因此我认为验证不起作用。

1 个答案:

答案 0 :(得分:1)

首先,请确保您的请求是POST或PUT

代替此操作

  

$ form-> submit(json_decode($ request-> getContent(),true));

执行以下操作:

$request->request->replace(json_decode($$request->getContent(), true));

然后强制表单处理请求,然后应用验证器

$form->handleRequest($request);

现在应该触发验证。