从ajax symfony2调用控制器的自定义功能

时间:2013-11-23 20:12:59

标签: symfony symfony-2.1 sonata-admin symfony-2.3 symfony-sonata

我使用Sonata Admin Bundle创建了表单。然后我创建了自己的Controller(TestController)并覆盖了CRUD控制器,

我在TestController中添加了一个新函数,

namespace IFI2\MainProjectBundle\Controller;

use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Bridge\Monolog\Logger;
use Sonata\AdminBundle\Controller\CRUDController as Controller;


//use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class TestController extends Controller
{

    public function getProductPricesAction() {

         file_put_contents("/Applications/XAMPP/htdocs/IFI2 CMS/Logs.txt","HELO",FILE_APPEND);

          return new Response(json_encode($response)); 

    }
}

然后我试图通过我的javascript代码

访问此功能
<script type="text/javascript">

    function test1() {

        $.ajax({
            type:"POST",
            //dataType: "json",
            url: '{{ path('main_project.admin.test')}}',
            success: function(successMsg) {
                alert("successMsg");

            },
            error: function(errorMsg) {
                alert("errorMsg");

            }
        });
     }

</script>

这是我的routing.yml,

main_project.admin.test:
  pattern:  /getProductPrices/
  defaults: { _controller: IFI2MainProjectBundle:Test:getProductPrices}

我已经有了这个实体的services.yml条目,

main_project.admin.cobrand:
    class: MainProjectBundle\Admin\TestAdmin
    arguments: [~, MainProjectBundle\Entity\Test, "MainProjectBundle:Test"]
    tags:
        - {name: sonata.admin, manager_type: orm, group: admin, label: Test}
    calls:
        - [setTemplate, [edit, MainProjectBundle:Test:edit.html.twig]]

我的回复中出现以下错误,

没有为控制器_sonata_admin定义MainProjectBundle\Controller\TestController和当前路由main_project.admin.test

请帮助我如何嵌入它?

谢谢, 费萨尔纳西尔

2 个答案:

答案 0 :(得分:3)

在Admin方法configureRoutes

中添加新路线
protected function configureRoutes(RouteCollection $collection)
{
    parent::configureRoutes($collection);
    $collection->add('get_product_prices');
}

删除你的路线main_project.admin.test

新路由的管理员使用$ baseRouteName作为前缀,并且名称为:

base_route_name_get_product_prices
使用

{{ path('base_route_name_get_product_prices') }}
//or with admin
{{ admin.generateUrl('get_product_prices') }}

答案 1 :(得分:0)

在routing.yml中添加以下内容:

main_project.admin.test:
  pattern:  /getProductPrices/
  defaults: { _controller: IFI2MainProjectBundle:Test:getProductPrices,"_sonata_admin": "main_project.admin.cobrand" }