首页 > 解决方案 > CakePHP 3.6.14:在数据库表的多列中搜索的自动完成字段

问题描述

我正在努力创建一个带有自动完成字段 ( Customer) 的表单。因此,当用户在此字段中键入一些字母时,运行查询将返回在或字段中包含这些字母的所有客户,name并且用户可以选择一个来完成表格。surnamecompany

这是客户的表单域:

添加.ctp

echo $this->Form->control('customer', ['id' => 'Autocomplete', 'empty' => true]);

这是Js函数:

<script type="text/javascript">
        $(document).ready(function(){
            // Caching the movieName textbox:
            var company = $('#Autocomplete');

            // Defining a placeholder text:
            company.defaultText('Search for customers');

            // Using jQuery UI's autocomplete widget:
            company.autocomplete({
                minLength    : 1,
                source        : 'getAll',
                select: function( event, ui ) {
                   event.preventDefault();
                   $(company).val(ui.item.id);
               },
            dataType: "jsonp",
            success: function( data ) {
                response( data );
            }
            });

        });

        // A custom jQuery method for placeholder text:

        $.fn.defaultText = function(value){

            var element = this.eq(0);
            element.data('defaultText',value);

            element.focus(function(){
                if(element.val() == value){ 
                    element.val('').removeClass('defaultText');
                }
                }).blur(function(){ 
                if(element.val() == '' || element.val() == value){ 
                    element.addClass('defaultText').val(value);
                }
            });

            return element.blur();
        }
</script>

控制器.php

这是包含查询的 getAll 函数:

public function getAll() {


        $this->autoLayout = false;
        $this->autoRender = false;


        $results = TableRegistry::get('Customers')->find('all', ['fields' => ['company', 'name', 'surname'], 
            'conditions' => [
                    'name LIKE' => '%'.$this->request->query('term').'%',
                    'company LIKE' => '%'.$this->request->query('term').'%',
                    'surname LIKE' => '%'.$this->request->query('term').'%',
            ]]);
        $response = array();
        $i = 0;
        foreach($results as $result){
           $response[$i] = $result['company'];

            $i++;

        }

       echo json_encode($response);

}

但是我没有得到任何结果...

标签: phpjquerysearchcakephpautocomplete

解决方案


推荐阅读