Question

My autocomplete is not working and I can't spot the error.

Jquery:

<script>
$(function() {
    $('#autoComplete').autocomplete({
        //source: "/groceries/items/autoComplete", ///This works but response isn't formatted correctly'
        //dataType: "json"
        minLength: 2,
        source: function( request, response ) {
            $.ajax({
                url: "/groceries/items/autoComplete",
                dataType: "jsonp",
                data: {
                    featureClass: "P",
                    style: "full",
                    maxRows: 12,
                    term: request.term
                },
                success: function( data ) {
                    response( $.map( data, function( el ) {
                        return { label: el.id, value: el.name }
                    }));
                }
            });
        }
    });
});

Controller:

public function autoComplete() {
        Configure::write('debug', 0);
        $this->layout = 'ajax';
        $query = $_GET['term'];
        $items = $this->Item->find('all', array(
            'conditions' => array('Item.name LIKE' => $query . '%'),
            'fields' => array('name', 'id', 'category_id'),
            'group' => array('name')));
        $this->set('items', $items);
    }

Form:

    <p>
    <?php echo $this->Form->create('Item', array('model'=>'item','action' => 'addItem', 'name'=>'AddItem'));?>
        <?php echo $this->Form->text('Item.name', array('size'=>'30', 'id'=>'autoComplete', 'autocomplete'=>'off')); ?>
        <?php echo $this->Form->text('Item.category_id', array('type'=>'hidden', 'value'=>'0')); ?>
        <?php echo $this->Form->text('Groclist.id', array('type'=>'hidden', 'value'=>$groclist['Groclist']['id'])); ?>
    <?php echo $this->Form->end('Add'); ?>
</p>

Response:

0: {Item:{name:Cake, id:6, category_id:null}}
1: {Item:{name:Carrot Cake, id:9, category_id:null}}
2: {Item:{name:Carrots, id:8, category_id:null}}
3: {Item:{name:Casserole, id:11, category_id:null}}
4: {Item:{name:Cauliflower, id:10, category_id:null}}

Edited for clarification.

I realize JqueryUI expects label and value and that map should rearrange them, but for some reason it's not. Any ideas?


I found an even better solution. This is done completely in the controller. No view required.

 public function autoComplete() {
        Configure::write('debug', 0);
        *$this->autoRender=false;*
        $this->layout = 'ajax';
        $query = $_GET['term'];
        $items = $this->Item->find('all', array(
            'conditions' => array('Item.name LIKE' => $query . '%'),
            'fields' => array('name', 'id', 'category_id'),
            'group' => array('name')));
        *$i=0;
        foreach($items as $item){
            $response[$i]['value']="'".$item['Item']['id']."'";
            $response[$i]['label']="'".$item['Item']['name']."'";
            $i++;
        }
        echo json_encode($response);*
    }
Was it helpful?

Solution

What if you reduce the array that is being returned by the Items model. So instead of $this->set('items', $items); you return the json encoded results like so:

foreach($items as $item) {
    $data[] = $item['Item'];
}
$data = json_encode($data);
echo $data;
exit;

This is inside the auto_complete method in the controller.

UPDATE: When querying for Cake for example, it would return a result like so:

[
  {"name":"Cake Batter","id":"1","category_id":"3"},
  {"name":"Cake Mix","id":"2","category_id":"3"}
]

if you are not wanting to return the json, you could just return $data without the json encoding.

Format Update:

I am not certain if this is to "sloppy", but you could change the foreach loop to:

foreach($items as $item) {
    $data[]= array(
        'label' => $item['Item']['name'],
        'value' => $item['Item']['id']
    );
}

OTHER TIPS

Looks like you forgot the Item:

response($.map( data, function( el ) {
    return { label: el.Item.id, value: el.Item.name }
});

You can also do it in the server side using Set:

$this->set('items', Set::extract('/Item', $items));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top