1

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>
ajwest
  • 258
  • 7
  • 17

1 Answers1

1

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) {
        /* .. */
    }
});

P.S.

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

b.b3rn4rd
  • 8,494
  • 2
  • 45
  • 57
  • I didn't realise that I had the encapsulation setup incorrectly. How are you using `Routing.generate`? I'm not exactly sure how to get access to that. – ajwest Feb 03 '15 at 06:44
  • Ok great, thanks for the help I've got that bundle now. When you're using the `Routing.generate` request, how do you catch the response in the controller? – ajwest Feb 03 '15 at 21:32
  • don't you think it's too many questions, probably you should ask separate questions :) Everything is as usual, `Routing.generate` only generates routes for you – b.b3rn4rd Feb 03 '15 at 21:37
  • How Do you get the 'id'? Is it stored in a hidden field? If so, how Do you Check that the id has not been manipulated by a user and simply changed to another id? – nova.cp Apr 27 '15 at 11:07
  • you can't check that in frontend, it's backend responsibility to check that user has rights to edit object – b.b3rn4rd Apr 27 '15 at 11:20