简体   繁体   中英

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

I'm trying to save a form with data that is received from an ajax request by the controller. I seem to have an issue binding the data to the new Symfony form in the controller. When the form with my data is received by the controller, logging shows that the isValid method seems to fail with [] []. I suspect there's a problem with my controller but I'm new to Symfony2 and unsure as to how to get my data to bundle with the form correctly.

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 Controller

 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));
}

Twig

<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>

I believe that the problem is that you are passing your form data in data element. While symfony expects form data in "root" of the $_POST array. If would suggest you to pass id as part of the url , however, if you want to stick to the original solution try something like:

    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');
                }
            });

When I need to submit a form using ajax, I usually use the following:

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

PS

I would suggest you to use JsonResponse if you are sending response in JSON format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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