0

I am struggling to create a form with an autocomplete field (Customer). So when the user types some letters in this field then the running query will return all customers which contain these letters in the name, surname or company fields and the user can select one to complete the form.

This is the form field for the customer:

add.ctp

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

This is the Js function:

<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>

Controller.php

This is the getAll function which contains the query:

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);

}

But I don't get any results...

dvn22
  • 151
  • 8
  • As a general note, **[controllers should not echo data](https://stackoverflow.com/questions/42378793/how-to-output-custom-http-body-contents-with-cakephp-3-4-echoing-causes-unable/42379581#42379581)**! – ndm Feb 15 '19 at 11:44
  • As ndm states, you need to return your data instead of doing an echo – proprit Feb 15 '19 at 16:36

0 Answers0