我正在使用Symfony2,并尝试在不重新加载页面的情况下创建新实体集合。我的控制器工作得很好,但我对Ajax有问题,我对它不太熟悉。当我按下提交按钮时,新实体会保存在数据库中,但实体不会出现在页面上。
集合控制器
/**
* @Route("/create-collection", name="collection_create_collection")
* @Template()
*/
public function createAction(Request $request)
{
$collection = new Collection();
$form = $this->createForm(
new CollectionType(),
$collection,
array('method' => 'POST',
'action' => $this->generateUrl('collection_create_submit'),
)
);
return array('collection'=>$collection, 'form' => $form->createView());
}
/**
* @Route("/collection_create_submit", name="collection_create_submit")
*/
public function createSubmitAction(Request $request)
{
$collection = new Collection();
$user = $this->getUser();
$form = $this->createForm(
new CollectionType(),
$collection,
array('method' => 'POST',
)
);
$form->handleRequest($request);
if ($form->isValid() && $form->isSubmitted()) {
$colname = $form["name"]->getData();
$existing = $this->getDoctrine()->getRepository('CollectionBundle:Collection')->findBy(['name' => $colname, 'user' => $user]);
if ($existing) {
return new JsonResponse(['error' => 'Collection with such name already exists']);
}
$em = $this->getDoctrine()->getManager();
$em->persist($collection);
$em->flush();
return new JsonResponse(array(
'success' => $collection
));
}
}
create.html.titch
{% include 'CollectionBundle:Collection:collectionJS.html.twig' %}
<div class="collection-create">
<h3 id="create-collection">Create a collection</h3>
<a class="close-reveal-modal" aria-label="Close">×</a>
{{ form_start(form, {'attr' : {'action' : 'collection_create_collection', 'id': 'create-collection-form'}}) }}
{{ form_widget(form) }}
<a class="button custom-close-reveal-modal" aria-label="Close">Cancel</a>
<button type="submit" value="create" class="right" onclick="createCollection();">Create</button>
{{ form_end(form) }}
</div>
<script type="application/javascript">
$('a.custom-close-reveal-modal').on('click', function(){
$('#externalModal').foundation('reveal', 'close');
});
</script>
collectionJS.html.titch
function createCollection(){
var $form = $('#create-collection-form');
$($form).submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize()
}).done(function( data ) {
if(data.error)
{
console.log(data.error);
} else if(data.success) {
var collection = data.success;
$('.griditems').prepend('<p>' + collection + '</p>');
$('#externalModal').foundation('reveal', 'close');
}
});
});
}
UPD
提交被触发,但现在我得到的是未定义的而不是实体。可能,我发送了错误的json响应。
UPD
我尝试对集合实体进行编码。在createSubmitAction中,我将返回更改为
$jsonCollection = new JsonEncoder();
$jsonCollection->encode($collection, $format = 'json');
return new JsonResponse(array(
'success' => $jsonCollection
));
如何在Ajax中获得此响应?
请查看此处提供的答案。如何在Symfony 2.0 AJAX应用程序中将Doctrine实体编码为JSON?
由于标准条令实体对象太大,您必须返回一个简单的$collection对象。我推荐的是:
return new JsonResponse(array(
'success' => $collection->toArray()
));
并在实体类中添加一个新方法:
public function toArray(){
return array(
'id' =>$this->getId(),
'name'=>$this->getName(),
// ... and whatever more properties you need
); }