Symfony 2自动完成路由

时间:2014-10-21 21:23:00

标签: forms symfony autocomplete

我安装此捆绑包:GenemuFormBudnle我尝试制作ajax自动填充功能。我的表格中有这个:

$builder
            ->add('PermitsCompany', 'genemu_jqueryautocompleter_entity', array(
                'route_name' => 'ajax_company',
                'class' => 'MainCoreBundle:Company',
            ));

这在我的控制器中: NewController.php

/**
     * @Route("/ajax_company", name="ajax_company")
     */
    public function ajaxCompanyAction(Request $request)
    {
        $value = $request->get('id');

        $permits = $this->getDoctrine()->getRepository('JokerCoreBundle:Company')->findAjaxValue($value);


        $json = array();
        foreach ($permits as $permit) {
            $json[] = array(
                'label' => $permit->getName(),
                'value' => $permit->getId()
            );
        }

        $response = new Response();
        $response->setContent(json_encode($json));

        return $response;
    }

这就是我的路线:

ajax_company:
  defaults: { _controller: MainCoreBundle:Permits:ajaxCompany}
  pattern:  /ajax_company/
  type:     annotation

以下是错误消息:

  

AnnotationException:[语义错误]注释“@Route”in   方法Main \ CoreBundle \ Controller \ NewController :: ajaxCompanyAction()   从未进口过。您是否忘记添加“使用”声明   这个注释?

1 个答案:

答案 0 :(得分:1)

您需要将以下行添加到Controller的顶部:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

如果没有它,Controller就无法从注释中正确加载Class。

正确的JSON响应也应正确设置Content-Type

$response = new Response(json_encode($json));
$response->headers->set('Content-Type', 'application/json');
return $response;

根据these docs,您的构建器稍有不正确。请改用:

$builder
    ->add('PermitsCompany', 'genemu_jqueryautocompleter_entity', array(
        'route_name' => 'ajax_company',
        'class' => 'MainCoreBundle\Entity\Company', // Must use namespace here with slashes
    ))
;

我已经检查了GenemuFormBundle存储库,看起来没有提供findAjaxValue函数或者将bundle注入到您的实体存储库中。您必须在存储库中创建findAjaxValue函数或恢复为辅助函数,例如findBy,如:

$permits = $this->getDoctrine()->getRepository('JokerCoreBundle:Company')->findBy(array(
    'name' => $value,
));

您尝试使用的捆绑包看起来不是一个完整的解决方案,也不打算成为一个解决方案:

  

这些实现中可能存在一些错误,这个包只是表单类型的一个概念,对于Symfony2项目非常有用。

也许你应该记住这一点并尝试提出自己的解决方案,或者找一个备用的包。