getDoctrine()在FOSUserBundle符号2中不起作用


getDoctrine() not working in FOSUserBundle symfony2

我需要创建一个状态下拉列表,这样只要我从country drop_down中选择country,就应该使用Ajax显示该country的states drop_down。我遇到了一个又一个错误。

尝试调用类"FOS''UserBundle''Controller''RegistrationController"的名为"getDoctrine"的未定义方法

AJAX被调用,国家的id被传递给控制器,主要问题是getDoctrine函数。这是我的控制器。

我是symfony的新手,请帮帮我。

public function getStateAction(Request $request)
    {               
            $em1 = $this->getDoctrine()->getManager();
            $data = $request->request->all();   
            $countryId = $data['id'];
            $repository = $em->getRepository('FOSUserBundle:State');
            $query = $repository->createQueryBuilder('p');
            $query->where('p.country ='.$countryId);
            $query->orderBy('p.id', 'ASC');
            $stateList = $query->getQuery()->getResult();
            //print_r($stateList); die;
    }

这是我的ajax

$(document).ready(function(){   
    $("#fos_user_registration_form_country_id").change(function(){
    var countryId = $(this).val();
             if(countryId!=0){
               $.ajax({
               type: "POST",
               url: "{{ path('fos_user_registration_country') }}",
               data: {id: countryId},
               cache: false,
               success: function(result){
               ("#fos_user_registration_form_state_id").append(result);
             }
           });
        }
    });
});

我假设您使用的FOSUserBundle版本不是最新的主版本。您的问题是因为在开发主版本之前,RegistrationController扩展了Symfony'Component'DependencyInjection'ContainerAware而不是Symfony'Bundle'FrameworkBundle'Controller'ControllerController类扩展了ContainerAware,并包含一组快捷方式调用,如getDoctrinegenerateUrlisGranted

getDoctrine方法只是调用容器,如。。

/**
 * Shortcut to return the Doctrine Registry service.
 *
 * @return Registry
 *
 * @throws 'LogicException If DoctrineBundle is not available
 */
protected function getDoctrine()
{
    if (!$this->container->has('doctrine')) {
        throw new 'LogicException('The DoctrineBundle is not registered in your application.');
    }
    return $this->container->get('doctrine');
}

您有两个选项:将getDoctrine方法复制到您的类中,或者直接使用$this->container->get('doctrine')

您尝试过:吗

public function getStateAction(Request $request)
{   
    $em1 = $this->container->get('doctrine')->getManager();
    /.../
}

getDoctrine()是类Symfony'Bundle'FrameworkBundle'Controller'Controller的一个方法,它不是从FOS'UserBundle'Controller'RegistrationController 扩展而来的

我将此行添加到我的控制器中,并且控制器是从容器而不是控制器继承的。谢谢你的帮助@scoolnico。

 public function getStateAction(Request $request)
        {               
                $em = $this->getDoctrine()->getManager();
                /../

        }