无法通过 ajax 在 symfony2 中保存实体,表单无效

Unable to save entity in symfony2 via ajax, form is invalid

我正在尝试保存一个表单,其中包含控制器从 ajax 请求中收到的数据。我似乎在将数据绑定到控制器中的新 Symfony 表单时遇到问题。当控制器接收到包含我的数据的表单时,日志记录显示 isValid 方法似乎因 [] [] 而失败。我怀疑我的控制器有问题,但我是 Symfony2 的新手,不确定如何让我的数据正确地与表单捆绑在一起。

jQuery Ajax POST

  $( document ).on( "submit", function(e){
            e.preventDefault();

            var $form = $('form.agency');

            var $url = $form.attr('action');

            var $data = $form.serialize();

            var $form_tag = $form.parent().attr('id').split('_');

            var $id = $form_tag[2];

            $.post($url, //ajax_return_agencies
                    {uid: $id, data: $data},
                    function (response) {
                        if(response.success) {
                            $('#result').html('SUCCESS');
                        }else{
                            alert('failed');
                        }
                    });
        });

Symfony2 控制器

 public function updateAction(Request $request)
{
    $logger = $this->get('logger');

    $id = $request->request->get('uid');

    $em = $this->getDoctrine()->getManager();
    $entity = $em->getRepository('ShuttleItGtfsBundle:ShuttleitAgencies')->find($id);
    $form = $this->createForm(new AgencyType(), $entity);
    $form->handleRequest($request);


    if ($form->isValid()) {

        $em->persist($entity);
        $em->flush();

        if($request->isXmlHttpRequest()) {
            $response = new Response();
            $output = array('success' => true);
            $response->headers->set('Content-Type', 'application/json');
            $response->setContent(json_encode($output));

            return $response;
        }
    }

    $errors = $form->getErrorsAsString();
    $errors = explode("\n", $errors);
    $response = array("code" => 100, "success" => false, "data_bundle" => $errors);
    return new Response(json_encode($response));
}

树枝

<h1>Agency creation</h1>
<span id="{{ type }}_form_{{ id }}">
<form class="{{ type }}" action="{{ path('set_element') }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form) }}
    <p>
        <button type="submit">Create</button>
    </p>
</form>
</span>
<ul class="record_actions">
    <li>
        <a href="#">
            Back to the list
        </a>
    </li>
</ul>
<div id="result"></div>

我认为问题在于您在 data 元素中传递表单数据。而 symfony 需要 $_POST 数组的 "root" 中的表单数据。 如果建议您将 id 作为 url 的一部分传递,但是,如果您想坚持原来的解决方案,请尝试类似的方法:

    var url = $('form.agency').attr('action');

    var data = $('form.agency').serialize();

    var form_tag = $('form.agency').parent().attr('id').split('_');

    var id = form_tag[2];
    data.id = id;

    $.post(url, data,
            function (response) {
                if(response.success) {
                    $('#result').html('SUCCESS');
                }else{
                    alert('failed');
                }
            });

当我需要使用ajax提交表单时,我通常使用如下:

  $.ajax({
    type: 'PUT',
    url: Routing.generate('frontend_edit_entity', {id:id}),
    data: data,
    dataType: 'json',
    success: function (response) {
        /* .. */
    }
});

P.S.

如果您以 JSON 格式发送回复,我建议您使用 JsonResponse