【问题标题】:Form: I don't get errors when I submit wrong data表单:提交错误数据时不会出错
【发布时间】:2013-08-08 16:28:09
【问题描述】:

我有这个验证表单的控制器代码(我将它用于 ajax 请求)。问题:当我提交错误的数据时,我没有收到任何错误,如下面的输出所示:

$app->post('/contacto', function (Request $request) use ($app) {


    $form = $app['form.factory']->createBuilder('form', $data)
        ->add('Nombre', 'text', array(
            'constraints' => new Assert\NotBlank(array('message' => 'El campo Nombre es obligatorio'))
        ))
        ->add('Email', 'text', array(
            'required' => false,
            'constraints' => new Assert\Email(array('message' => 'Has introducido un email no válido. Revísalo, por favor.')),
        ))
        ->add('Telefono', 'text', array(
            'label' => 'Teléfono',
            'constraints' => array(
                new Assert\Regex(array('pattern' => "/^(?:\d\s*){8}\d$/", 'message' => 'El teléfono debe tener 9 dígitos')),
                new Assert\NotBlank(array('message' => 'El campo Teléfono es obligatorio')),
            )))
            ->add('Texto', 'textarea', array(
                'constraints' => new Assert\NotBlank(array('message' => 'El campo Texto es obligatorio')),
                'attr' => array('cols' => '76', 'rows' => '8'),
            ))
            ->getForm();

    $post = $request->request->get('form');

    $form->bind($post);

    if ($form->isValid()) {
        $data = $form->getData();

         $app['mailer']->send($message);

        $my_array = array('Gracias, hemos recibido tu mensaje, te contactaremos lo antes posible');

        return new Response('true');
    } else {
        var_dump($form->getData());
        var_dump($form->getErrors());
        die("jfklas");
        return new Response(json_encode($form));
    }
});

array(4) {
  ["Nombre"]=>
  string(8) "fasdfasd"
  ["Email"]=>
  string(5) "fasdf"
  ["Telefono"]=>
  string(7) "9999999"
  ["Texto"]=>
  string(7) "fasdfas"
}
array(0) {
}
jfklas

【问题讨论】:

  • 断言不是空白有效吗?
  • 尝试检查$form->getErrorsAsString()函数的输出

标签: forms symfony silex


【解决方案1】:

$form->getErrors() return 只返回表单本身的错误,不返回子字段的错误。如果指定字段,则可能会出错,例如使用$form['Telefono']->getErrors() 或使用$form->getErrorsAsString()

【讨论】:

    【解决方案2】:

    如果你想使用 getErrors,你需要在表单项中添加 error_bubbling

        ->add('Nombre', 'text', array(
            'error_bubbling' => true, 'constraints' => new Assert\NotBlank(array('message' => 'El campo Nombre es obligatorio'))
        ))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 2014-02-25
      • 2018-11-24
      • 2017-08-24
      • 2011-01-06
      • 1970-01-01
      相关资源
      最近更新 更多