收集字段上的验证组

问题描述 投票:0回答:1

嗨我有收集类型这样的问题

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

CriteriaForm看起来像这样

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,我发现数据在验证之前映射到对象,这就是问题所在。我的对象异常,所以我认为验证不起作用。

php symfony symfony-forms symfony4
1个回答
1
投票

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

而不是这样做

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

做这个:

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

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

$form->handleRequest($request);

现在应该触发验证。

© www.soinside.com 2019 - 2024. All rights reserved.