2017-06-09 140 views
0

我想知道,如何在cakephp 2中创建自动完成。我在网上阅读,但我找不到有关我的部分的相关信息。自动完成Ajax上cakephp 2

当前我先在控制器中加载所有数据,分配给视图,然后从所有数据开始自动完成。但由于数据可能很多,这样效率不高,需要时间。我怎么能过滤控制器功能加载只关键字我输入类型?我能够做到这一点PHP的水平,但我dunt知道如何介绍CakePHP 2.

这里我介绍CakePHP 2现行规范:

ProductController的这个加载所有产品的专卖店:

$storeproducts = $this->get_storeproduct_autocomplete($sale['Sale']['store_id']); 

这是我的看法,输入:

<input type="text" class="form-control" placeholder="Barcode/Nama barang..." name="search_keyword" id="searchProduct" /> 

,并在视图的底部我把剧本:

$(function() { 
     var availableProduct = [ 
     <?php 
     foreach ($products as $spro): 
      $label = addslashes($spro['Product']['barcode'].' '.$spro['Product']['product_name']); 

      ?> 
      { label:"<?php echo $label;?>", value:"<?php echo $spro['Product']['barcode'];?>" }, 
      <?php 
     endforeach; 
     unset($spro); 
     ?> 
     ]; 
     $("#searchProduct").autocomplete({ 
      source: availableProduct, 
      delay: 200, 
      minLength: 2 
     }); 
    }); 

通过使用这些代码,自动完成工作,但它首先加载整个记录,而不是我输入的过滤器。并且输入字段用条形码填充,或者我设置的任何值,但是我希望它显示产品名称,并且当我提交时,它具有产品ID,我们可以这样做吗?

编辑1: 更新我的控制器,创建新的函数来做到这一点通过AJAX调用数据过滤器:

public function ajax_get_autocomplete_storeproduct($keyword, $store_id) 
    { 
     $result = array(); 

     $storeproducts = $this->StoreProduct->find('all', array(
      'fields'=>array('StoreProduct.id', 'StoreProduct.stok'), 
      'conditions'=>array('Product.deleted'=>0, 
           'StoreProduct.stok >'=>0, 
           'StoreProduct.store_id'=>$store_id, 
           'OR'=>array(
            'Product.barcode LIKE' => "%$keyword%", 
            'Product.product_name LIKE' => "%$keyword%", 
           ) 
           ))); 

     //how to set the value to view ? 

     return new CakeResponse(array('body'=>json_encode($result))); 
    } 

如何设置的关键:从数值控制器在阿贾克斯数据响应?

+0

您可以使用自动完成引导是 –

+0

有文档页面是什么? – Gabriel

回答

1

你可以做的是,你可以在自动完成中调用ajax函数。所以在页面加载时,你不必做任何事情。但在键类型上,将调用ajax函数。

$("#searchProduct").autocomplete({ 
    source: function (request, response) { 
      $.ajax({ 
       url: "add url for function call in ajax", 
       dataType: "json", 
       type: "post", 
       data: {key: value},// if you want to send any values to ajax call, you can do it here. 
       success: function (data) { 
        response(data); 
       } 
      }); 
     }, 
     minLength: 2, 
     delay: 200// im not sure why u need delay. 
}); 

在该功能为这AJAX调用去,填充阵列有和回声使用echo json_encode($array); JSON格式的阵列。它会工作。

编辑

你的控制器功能,应该是这样的

function products() { 
    $array[0]['name'] = "Product - 1"; 
    $array[0]['price'] = 100; 
    $array[1]['name'] = "Product - 2"; 
    $array[1]['price'] = 200; 
    // like above populate all your products in to an array. 

    // at last add this line 
    echo json_encode($array);// this will generate key: value what you asked. 
} 
+0

IC ..但我怎么能发送数据格式的键:从控制器的价值? *我更新我的问题qith更新的控制器代码?只是在控制器上找到列表? – Gabriel

+0

@Gabriel,检查我的编辑。 –

+0

自动完成功能无法正常工作,我们是否需要图书馆来做到这一点?而不是jQuery – Gabriel