【问题标题】:Symfony 2 autocomplete routingSymfony 2 自动完成路由
【发布时间】:2014-10-21 21:22:59
【问题描述】:

我安装了这个包: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: [Semantical Error] 注解“@Route”在 方法 Main\CoreBundle\Controller\NewController::ajaxCompanyAction() 从来没有进口过。您是否可能忘记为 这个注释?

【问题讨论】:

    标签: forms symfony autocomplete


    【解决方案1】:

    您需要将以下行添加到控制器的顶部:

    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 函数或将捆绑包注入到您的实体存储库中。您必须在存储库中创建 findAjaxValue 函数或恢复为辅助函数,例如 findBy,如下所示:

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

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

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

    也许您应该牢记这一点,并尝试提出自己的解决方案,或者寻找替代捆绑包。

    【讨论】:

    • 现在错误消失了,谢谢:) 但是你知道为什么自动完成仍然没有工作吗?我有一个空的文本输入,但是当我输入一些内容时它不会自动完成它......
    • 这是路由问题吗?
    • @Cre3k 您应该检查开发人员工具或 Firebug 中的控制台和网络选项卡,具体取决于您使用的浏览器。您是否尝试直接在浏览器中加载 /ajax_company 路由?
    • 未定义方法'findAjaxValue'。
    • @Cre3k 所以你应该从那里开始......没有你的前端代码我帮不了你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多