无法从Symfony Form 4.2获取错误消息

时间:2019-01-21 19:32:41

标签: php forms symfony

我以独立方式使用Symfony Form 4.2。我有一个表单元素,HTML文件中的字段很少。为了同样在PHP中进行验证,我使用Symfony Form 4.2在PHP中复制了表单,如下所示:

    $formFactory = Forms::createFormFactoryBuilder()
    ->addExtension(new ValidatorExtension($validator))
    ->getFormFactory();

    $form = $formFactory->createBuilder()
    ->add('pk_firstname', TextType::class, [
        'constraints' => [new NotBlank(),
            new Length([
                    'min' => 2,
                    'max' => 50,
                    'minMessage' => 'Your first name must be at least {{ limit }} characters long',
                    'maxMessage' => 'Your first name cannot be longer than {{ limit }} characters']
            )],
    ])
    ->add('pk_lastname', TextType::class, [
        'constraints' => [new NotBlank(),
            new Length([
                    'min' => 2,
                    'max' => 50,
                    'minMessage' => 'Your first name must be at least {{ limit }} characters long',
                    'maxMessage' => 'Your first name cannot be longer than {{ limit }} characters']
            )],
    ])
    ->add('pk_emailaddress', EmailType::class, [
        'constraints' => [new NotBlank(), new Email(
            [
                'message' => 'The email "{{ value }}" is not a valid email.',
                'mode' => 'strict',
            ]
        )],
    ])
    ->add('pk_phonenumber', TelType::class, [
        'constraints' => [],
    ])
    ->add('pk_message', TextareaType::class, [
        'constraints' => [new NotBlank()],
    ])
    ->getForm();

在前端提交表单时,我会使用JavaScript防止默认行为,并使用提交的数据向PHP文件发出AJAX请求,其中Symfony表单用于验证提交的数据的正确性。

然后,我手动提交如下表格:

    $request = Request::createFromGlobals();

$submitData = array("pk_firstname" => $request->request->get('pk_firstname'),
    "pk_lastname" => $request->request->get('pk_lastname'),
    "pk_emailaddress" => $request->request->get('pk_emailaddress'),
    "pk_phonenumber" => $request->request->get('pk_phonenumber'),
    "pk_message" => $request->request->get('pk_message'));

$form->submit($submitData);

这里的问题是,在isValid()对象上通过$form方法提交了无效数据后,返回了表格无效,但是getErrors()方法返回了空数组。

在这里我做错了什么吗?

我想获取违反约束条件和约束条件的字段,以便将这些错误消息传递给JavaScript以显示在前端。

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么您只想序列化一个表单对象,对吧?

因此,您可以执行以下操作:

 public function getErrorMessages(FormInterface $form)
    {
        $errors = array();
        foreach ($form->getErrors(true, true) as $error) {
            $propertyPath = str_replace('data.', '', $error->getCause()->getPropertyPath());
            $errors[$propertyPath] = $error->getMessage();
        }

        return $errors;
    }

您必须将表单对象传递给此方法,例如$serializedErrors = getErrorMessages($form)