繁体   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