如何执行正确的路线? symfony的

时间:2016-06-30 13:10:40

标签: backbone.js symfony

我使用骨干,我想用collection.create()方法将新模型保存到数据库中。

我在Symfony中有两条具有相同名称/文档的路由。这两条路由具有不同的方法,用于查询对象的第一路径和用于将对象保存到数据库的第二路径。那么如何指定将对象保存到数据库的路由?有可能吗?

这是我的控制器,但是symfony为我创建了documentAction()方法和createAction方法的路由器。因为当我在控制台中写入以查看我的路由器的名称时使用php bin / console debug:router我看到它是由symfony制作的。

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use AppBundle\Entity\Document;
use Doctrine\ORM\Mapping as ORM;


class DocumentQuery extends Controller
{
    /**
     * @Route("/doc")
     * @Method({"GET"})
    */
    public function documentAction()
    {
        $id = $this->getUser()->getId();

    $em = $this->getDoctrine()->getManager();
    $documents = $em->getRepository('AppBundle:Document')->findAllOrderedById();
    $titles = array();

    foreach($documents as $document) 
    {
        $user_id = $document['user_id'];
        $title = $document['title'];

        if($user_id == $id)
        {
            $titles[] = $document;
        }             
    }

    return new JsonResponse($titles);

    //return new JsonResponse($document);
    //return new JsonResponse($documents);
    //dump(json_encode($documents));
    //return $this->render('default/doc.html.twig', array('documents' => $documents, 'id' => $id));
}

/**
 * @Route("/doc")
 * @Method({"POST"})
*/
public function createAction(Request $request)
{
    $content = $request->getContent();

    $document = new Document();

    $document->setTitle($request->get('title'));
    //$document->setBody($content);

    $em = $this->getDoctrine()->getManager();
    $em->persist($document);
    $em->flush();

    return new JsonResponse($document);
}
}

收藏:

var User = Backbone.Collection.extend({
        model: DocumentUser,
        url: '/doc',
        initialize: function(){
                this.fetch();
                console.log(this, "this.collection");
        },

});

Collection.create:

save: function()
        {

                this.collection.create({
                        title: $("#title").val()
                });
                console.log(this.collection);
        }

路由yml。我是用您发布的代码制作的:

app:
    resource: "@AppBundle/Controller/"
    type:     annotation

document_query:
    path:     /doc
    defaults: { _controller: AppBundle:Controller:DocumentQuery:documentAction}
    methods: [GET]

document_save:
    path:     /doc
    defaults: { _controller: AppBundle:Controller:DocumentQuery:createAction}
    methods: [POST]

Here is the router, you can see app_documentquery_document and app_documentquery_create is made by symfony, and the document_query and document_save i made in routing.yml

0 个答案:

没有答案