CakePHP & jQuery UI Autocomplete

Written by James McDonald

July 20, 2015

This is a field that you enter a partial “batch” number and then the JQuery Autocomplete control queries the remote database for a matching list.

batch

This is rough code to get a jQuery UI auto complete control working with CakePHP.

// in Model/Label.php

     public function batch_lookup($term) {

        $options = [
            'fields' => [
                'Label.batch',
                'Label.print_date'
            ],
            'conditions' => [
                'Label.batch LIKE' => '%' . $term . '%'
            ],
            'group' => [
                'Label.batch'
            ],
            'recursive' => -1
        ];

        $batches = $this->find('all', $options);

        $batches = Hash::map($batches, '{n}.Label', [ $this, 'fmt_batch']);
        return $batches;
        
    }

    public function fmt_batch($data) {

        return [
            'value' => $data['batch'],
            'label' => $data['batch'] . " - " 
            . CakeTime::format(
                    $data['print_date'], 
                    '%a %d/%m/%Y', 
                    'invalid'
                 )
        ];
    }

In the Controller

// In Controller/LabelsController.php

    public function batch_lookup() {

        Configure::write('debug', 0);
        $this->layout = 'ajax';
        $this->view = '/Labels/batches';
        $search_term = $this->request->query['term'];

        $batches = $this->Label->batch_lookup($search_term);

        $this->set(compact('batches'));
    }

 

// View/Label/lookup.ctp


<?php $this->Html->css('lookup/lookup', array('inline' => false)); ?>

<?php
$this->Html->script(array(
    'external/jquery/jquery',
    // include jquery and ui
    'jquery-ui.min',
    // this has the jquery initialization code
    'lookup/lookup'
        ), array(
    'inline' => false,
    'block' => 'script_bottom'
        )
);
?>
<?php echo $this->Form->create('Lookup', array('url' => array('controller' => 'labels', 'action' => 'lookup_search'))); ?>

<legend><?php echo __('Search Conditions'); ?></legend>
 
<?php echo $this->Form->input('batch', array(
        'id' => 'batch',
        'data-submit_url' => $this->base . '/' . $this->params['controller'] . '/batch_lookup',
        'type' => 'text',
        'div' => array('class' => 'form-cell'))); ?> 
<?php echo $this->Form->end(__('Search'), array('class' => 'form-cell')); ?>

 

The HTML of the input looks like this:

 

<!-- the input looks like this when 
     rendered as HTML -->
    
    <div class="form-cell">
        <label for="batch">Batch</label>
        <input name="data[Lookup][batch]" 
               id="batch" 
               data-submit_url="/wms/labels/batch_lookup" 
               empty="" 
               type="text" 
               class="ui-autocomplete-input" 
               autocomplete="off">
    </div>

<!-- the data-submit_url element allows you to dynamically specify 
     the autocomplete lookup url -->

 

    // jquery code wrap this in a $(document).ready(function(){})
    // block
    batch = $("#batch"); 
    submit_url = batch.attr('data-submit_url');
    // actually you can access the information using
    submit_url = batch.data('submit_url');
    
    batch.autocomplete({
            source: submit_url,
            minLength: 2
    });

The json out put view file View/Label/batches.ctp

<?php
echo json_encode($batches);
?>

I am using the Hash::map CakePHP function to modify the returned data so that I can have the correct JSON output but this link has a nice write up on how to reformat your JSON using JQuery.

Shear brilliance: http://www.jensbits.com/2011/08/24/using-jquery-autocomplete-when-remote-source-json-does-not-contain-label-or-value-fields/

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…

How to Research a CPU Upgrade

How to Research a CPU Upgrade

Upgrade Time! Doing a lot of VMWare Workstation virtualization to create labs for self-study and training. Finding...