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>