Symfony2表单:在Ajax成功创建实体

时间:2015-11-09 11:29:53

标签: php jquery ajax symfony

我正在使用Symfony2,我正在尝试创建新的实体 Collection ,而无需重新加载页面。我的控制器工作正常,但我有Ajax的问题​​,我不熟悉它。以下是我已经拥有的代码。当我按下提交按钮时,新实体将保存在数据库中,但实体不会显示在页面上。

CollectionController

/**
 * @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.twig

 {% 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">&#215;</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.twig

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

触发提交,但现在我得到 undefined 而不是实体。可能是,我发送了错误的json回复。

UPD

我尝试编码收集实体。 在createSubmitAction中,我改变了返回

  $jsonCollection = new JsonEncoder();
        $jsonCollection->encode($collection, $format = 'json');

        return new JsonResponse(array(
            'success' => $jsonCollection
        ));

如何在Ajax中获得此响应?

2 个答案:

答案 0 :(得分:2)

JsonResponse无法将您的实体转换为JSON。您需要使用像JMSSerializerBundle这样的序列化程序库,或在您的实体中实现序列化方法。

检查此处提供的答案。 How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

答案 1 :(得分:0)

您必须返回一个简单的$ collection对象,因为标准的doctrine实体对象的大小太大。我建议的是:

return new JsonResponse(array(
        'success' => $collection->toArray()
    ));

并向您的实体类添加新方法:

public function toArray(){

return array(
'id'  =>$this->getId(),
'name'=>$this->getName(),
// ... and whatever more properties you need
); }