【问题标题】:Symfony2: getting form validation error on repeated fieldSymfony2:在重复字段上获取表单验证错误
【发布时间】:2012-12-12 16:39:16
【问题描述】:

我设置了一个非常基本的表单来注册用户(用户名 + 密码)。我想在我的控制器中获取验证错误。

我找到了两种方法:

// In my controller:
$user = new User();
$form = $this->createForm(new UserType, $user);

$request = $this->get('request');

if($request->getMethod() == 'POST') {
     $form->bind($request);

     if($form->isValid()) {
         // save user in DB
     } else {
         // First way
         $errors = $this->get('validator')->validate($user);

         // OR
         $errors = $form->getErrors();
     }
 }

例如,如果我在表单中输入的用户名太短,这两种方法都有效(此字段有 MinLength 约束)。但是如果我输入了两个不同的密码,则表单无效,并且在 $form->getErrors() 或 $this->get('validator')->validate($user) 中没有消息错误。我怎样才能得到这个错误信息?

这是我构建表单的方式

$builder->add('username', 'text', array(
    'attr' => array(
       'placeholder' => 'Choose an username'
    ),
    'label' => 'Username *',
    'error_bubbling' => true,
));

$builder->add('password', 'repeated', array(
    'type' => 'password',
    'invalid_message' => 'The password fields must match.',
    'required' => true,
    'first_options'  => array(
        'label' => 'Password',
        'attr' => array('placeholder' => 'Enter password')
    ),
    'second_options' => array(
        'label' => 'Repeat Password',
        'attr' => array('placeholder' => 'Retype password')
    ),
    ));

【问题讨论】:

    标签: php symfony


    【解决方案1】:

    为什么要在控制器中获取此消息?

    无论如何,您必须为 'password' 字段类型调用 getErrors()。 这应该会给你'The password fields must match.' 错误。

    $passwordErrors = $form->get('password')->getErrors();
    
    foreach ($passwordErrors as $key => $error) {
          $message .= $error->getMessageTemplate(). '<br/>';
    }
    

    error_bubbling 选项用于将给定字段的任何错误传递给父字段或表单。在您的示例中,error_bubblingusername 设置为 true,因此您可以通过在父元素(此处为 $form)上调用 getErrors() 来获取用户名字段验证错误消息。除非您也将此特定字段的 error_bubbling 选项设置为 true,否则密码重复字段不是这种情况。

    【讨论】:

    • 感谢您的回答,但它不起作用。它返回一个空数组。我想这样做的原因是因为我尝试通过 ajax 验证此表单:我想以 JSON 格式返回一个包含验证错误列表的响应。
    • 我刚刚使用您自己的代码对其进行了测试,它工作正常,我更新了我的答案。将密码重复字段的 error_bubling 设置为 true。然后,您可以使用 $form->getErrors() 获取错误。
    【解决方案2】:

    在我的情况下,经过多次尝试,这是最终的解决方案......

    FIRST:设置为 false error_bubbling(或者不设置,因为 false 是默认值)。

    SECOND:使用以下代码获取field => error_message 数组。

        $errors = array();
        foreach ($form->all() as $child) {
            $fieldName = $child->getName();
            $fieldErrors = $form->get($child->getName())->getErrors(true);
    
            foreach ($fieldErrors as $fieldError){
                $errors[$fieldName] = $fieldError->getMessage();
            }
        }
    

    此代码应该适用于 Symfony 3.4 / 4.1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      相关资源
      最近更新 更多