如何在cakephp中实现搜索栏自动完成功能

时间:2017-11-18 06:20:43

标签: cakephp cakephp-2.0 jquery-ui-autocomplete

我想将下面的自动完成代码集成到我的CakePHP代码中。主要是我想从数据库(制造商+产品,例如:BMW X5)中提取数据,而不是从以下代码中的数组availableTags中提取数据。

我不是CakePHP的专家,那么如何将数组availableTags替换为CakePHP数据库函数呢?

产品表列:Id,product_name,version,manufacturer_id,category id

制造商表格列:id,制造商

Search.html

 <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>jQuery UI Autocomplete - Default functionality</title>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">


      <?php App::import('Controller','Products');App::import('Controller','Manufacturers');

<link rel="stylesheet" href="/resources/demos/style.css">
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script>
      $( function() {
        var availableTags = [
          "ActionScript",
          "AppleScript",
          "Asp",
          "BASIC",
          "C",
          "C++",
          "Clojure",
          "COBOL",
          "ColdFusion",
          "Erlang",
          "Fortran",
          "Groovy",
          "Haskell",
          "Java",
          "JavaScript",
          "Lisp",
          "Perl",
          "PHP",
          "Python",
          "Ruby",
          "Scala",
          "Scheme"
        ];
        $( "#tags" ).autocomplete({
          source: availableTags
        });
      } );
      </script>
    </head>
    <body>

    <div class="ui-widget">
      <label for="tags">Tags: </label>
      <input id="tags">
    </div>

产品控制器

public function suggestion() {
        $this->autoRender = false;

        $query = $this->params['url']['term'];

        $return_arr = array();
        $products = $this->Product->find('all', array('fields' => array('DISTINCT (Product.product_name) AS product_name'),'conditions' => array('Product.product_name LIKE' => $query.'%')));

        foreach($products as $product) {
            $return_arr[] = $product['Product']['product_name'];
        }


        echo json_encode($return_arr);

     }?>

制造商控制器

public function suggestion() {
            $this->autoRender = false;

            $query = $this->params['url']['term'];

            $return_arr = array();
            $manufacturers = $this->Manufacturer->find('all', array('fields' => array('Manufacturer.manufacturer'),'conditions' => array('Manufacturer.manufacturer LIKE' => $query.'%')));

            foreach($manufacturers as $manufacturer) {
                $return_arr[] = $manufacturer['Manufacturer']['manufacturer'];
            }


            echo json_encode($return_arr);

        }?>

1 个答案:

答案 0 :(得分:0)

您可以在获取产品时将制造商表与产品表绑定,然后在产品控制器中绑定,您可以使用虚拟字段来组合值