我正在尝试使用Symfony创建AJAX表单,但我的表单返回空对象。当我发送manualy写文本或数组时,一切正常。这个bug在哪里?我对表单或javascript代码做错了什么问题?
/**
* 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;
}
}
和Javascript代码:
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);
}
});
});
}
答案 0 :(得分:1)
今天有同样的问题,版本2.8会留在这里,以防它最终痊愈别人我已将此添加到我的表单构建器
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return '';
}