Reputation: 356
I'm trying to create AJAX form with Symfony, but my form return empty object. When I send manualy writed text or array everything works fine. Where is the bug? I do something wrong with form or javascript code is the problem?
/**
* Renders the "new" form
*
* @Route("/", name="demo_new")
* @Method("GET")
*/
public function newAction(Request $request) {
$entity = new Demo();
$form = $this->createForm(DemoType::class, $entity);
return $this->render('default/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
)
);
}
/**
*
* @Route("/", name="demo_create")
* @Method("POST")
*
*/
public function createAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}
$entity = new Demo();
$form = $this->createForm(DemoType::class, $entity, array(
'action' => $this->generateUrl('demo_create'),
'method' => 'POST',
));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
return new JsonResponse(
[
'message' => 'Success!',
'data' => $data
], 200);
}
$response = new JsonResponse(
array(
'message' => 'Error',
'form' => $this->renderView('default/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
))), 400);
return $response;
}
}
and Javascript code:
function initAjaxForm()
{
$('body').on('submit', '.ajaxForm', function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
})
.done(function (data) {
if (typeof data.message !== 'undefined') {
console.log(data.data);
console.log(data.message);
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof jqXHR.responseJSON !== 'undefined') {
if (jqXHR.responseJSON.hasOwnProperty('form')) {
$('#form_body').html(jqXHR.responseJSON.form);
}
$('.form_error').html(jqXHR.responseJSON.message);
} else {
alert(errorThrown);
}
});
});
}
Upvotes: 1
Views: 781
Reputation: 36
Had same issue today with version 2.8 gonna leave this here in case it end up healping someone else i've added this to my form builder
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return '';
}
Upvotes: 1