簡體   English   中英

Symfony2形式:在Ajax成功上創建實體

[英]Symfony2 form: create entity on Ajax success

我正在使用Symfony2,並且嘗試創建不重新加載頁面的新實體集合 我的控制器工作正常,但是我對Ajax有問題,對此我不太熟悉。 以下是我已經擁有的代碼。 當我按下提交按鈕時,新實體會保存在db中,但實體不會出現在頁面上。

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,而不是entity。 可能是我發送了錯誤的json響應。

UPD

我試圖對集合實體進行編碼。 在createSubmitAction中,我將return更改為

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

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

如何在Ajax中獲得此響應?

JsonResponse無法將您的實體轉換為JSON。 您需要使用諸如JMSSerializerBundle之類的序列化程序庫,或者在您的實體中實現序列化方法。

檢查此處提供的答案。 如何在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
); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM