简体   繁体   English

Ajax中的Symfony2表单验证

[英]Symfony2 form validation in Ajax

On certain pages I use forms within bootstrap modals. 在某些页面上,我使用bootstrap模式中的表单。 I submit the form with Ajax and it gets validated in the controller. 我使用Ajax提交表单,并在控制器中进行验证。 The most users will fill in the form correctly but if a validation fails the form is re-rendered and got send back to the user. 大多数用户将正确填写表单,但如果验证失败,表单将重新呈现并发送回用户。 I don't like this at all, but I can't find a better way because I can't get access the validation errors of the fields. 我根本不喜欢这个,但我找不到更好的方法,因为我无法访问字段的验证错误。 Does someone has a better approach to achieve validation errors send back in JSON? 有人有更好的方法来实现以JSON发回的验证错误吗?

I created a function myself 我自己创建了一个函数

public function getFormErrors(Form $form) {
    $errors = $form->getErrors();
    foreach ($form->all() as $child) {
        foreach ($child->getErrors() as $key => $error) {
            $template = $error->getMessageTemplate();
            $parameters = $error->getMessageParameters();

            foreach ($parameters as $var => $value) {
                $template = str_replace($var, $value, $template);
            }

            $errors[$child->getName()][] = $template;
        }
    }
    return $errors;
}

if I understand right you have a form and you need to get the errors for each field separately. 如果我理解你有一个表格,你需要分别得到每个字段的错误。 if so, have a look at \\Symfony\\Component\\Form\\Form::getErrorsAsString() & do smth of the kind: 若是,请查看\\ Symfony \\ Component \\ Form \\ Form :: getErrorsAsString()&do smth of the kind:

function getFormErrors($form)
{
    $errors = array();

    // get the form errors
    foreach($form->getErrors() as $err)
    {
        // check if form is a root
        if($form->isRoot())
            $errors['__GLOBAL__'][] = $err->getMessage();
        else
            $errors[] = $err->getMessage();
    }

    // check if form has any children
    if($form->count() > 0)
    {
        // get errors from form child
        foreach ($form->getIterator() as $key => $child)
        {
            if($child_err = getFormErrors($child))
                $errors[$key] = $child_err;
        }
    }

    return $errors;
}

I'd say that the cleanest solution is to implement JMSSerializerBundle ( http://jmsyst.com/bundles/JMSSerializerBundle ) which uses the following Class: 我要说最干净的解决方案是实现使用以下类的JMSSerializerBundlehttp://jmsyst.com/bundles/JMSSerializerBundle ):

https://github.com/schmittjoh/serializer/blob/6bfebdcb21eb0e1eb04aa87a68e0b706193b1e2b/src/JMS/Serializer/Handler/FormErrorHandler.php https://github.com/schmittjoh/serializer/blob/6bfebdcb21eb0e1eb04aa87a68e0b706193b1e2b/src/JMS/Serializer/Handler/FormErrorHandler.php

then in your controller : 然后在你的控制器中

        // ...
        if ($request->isXMLHttpRequest()) {
        $jsonResponse = new JsonResponse();

        $serializer = $this->container->get('jms_serializer');
        $form = $serializer->serialize($form, 'json');

        $data = array('success' => false,
                       'errorList' => $form);

        $jsonResponse->setData($data);

        return $jsonResponse;
    }

I just have the same problem Today ! 我今天也遇到同样的问题!

I sent the form with ajax, and if my controller sent me not a json 'OK', the form is refresh with the new form sent by the controller, who contains errors. 我用ajax发送了表单,如果我的控制器发送给我的不是json'OK',表单会刷新控制器发送的新表单,其中包含错误。 Data 'OK' is sent when form->isValid(), else it return the form render. 当form-> isValid()时发送数据'OK',否则它返回表单渲染。

HTML : HTML:

<div class="form_area">
     <form id="myform" action.... >
           ...code form ...
     </form>
</div>

Controller Action: 控制器动作:

use Symfony\Component\HttpFoundation\JsonResponse;

public function myEditAction(){
    .......
    if ( $request->getMethod() == 'POST' ) {
        $form->bind($request);

        if ($form->isValid()) {
            ... code whn valide ...
            if ( $request->isXmlHttpRequest() ) {
                return new JsonResponse('OK');
            }
        }
    }

    return $form;
}

JS: JS:

$('#myform').on('submit',function(e){
            var formdata = $('#myform').serialize();
            var href = $(this).attr('action');
            $.ajax({
                type: "POST",
                url: href,
                data: formdata,
                cache: false,
                success: function(data){
                    if(data != "OK") {
                        $('.form_area').html(data);
                    } 
                },
                error: function(){},
                complete: function(){}
            });
            return false;
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM