1

I am working with Symfony2 and I am trying to create new entity Collection without page reload. My controller works fine, but I have issues with Ajax, I am NOT well familiar with it. Below is the code I already have. When I press submit button, new entity is saved in db, but entity doesn't appear on page.

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

The submit is triggered, but now I get undefined instead of entity. Probably, I am sending wrong json response.

UPD

I tried to encode collection entity. In createSubmitAction I changed return to

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

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

How do I get this response in Ajax?

user3793667
  • 321
  • 1
  • 6
  • 18
  • Take a look here: http://stackoverflow.com/questions/6706485/how-to-encode-doctrine-entities-to-json-in-symfony-2-0-ajax-application – Atan Nov 09 '15 at 11:53
  • on first look it seems like createCollection(); (js function) is a function that binds an (not defined) variable form's submit ... is the button actually triggering the bind and the submit ? did you check if the submit is triggered in your javascript ? – nixoschu Nov 09 '15 at 12:03
  • @nixoschu the submit didn't trigger, but I fixed it. Now it triggers, but I don't receive entity – user3793667 Nov 09 '15 at 12:25
  • Is the entity at least saved in DB but not returned ? Than the next thing really is what @Atan answered to you, take a look at that – nixoschu Nov 09 '15 at 12:31

2 Answers2

2

JsonResponse cannot transform your entities into JSON. You need to use a serializer library like JMSSerializerBundle or implement a serializing-method inside your entity.

Check the answers provided here. How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

Community
  • 1
  • 1
Atan
  • 1,095
  • 2
  • 12
  • 17
0

You have to return a simple $collection object as the standard doctrine entity objects are too large in size. What I recommend is:

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

and adding a new method to your entity class:

public function toArray(){

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