Reputation: 2011
I am trying to get Ajax autocomplete setup for a textbox in CakePhp 2.x.
In my view I have:
<?php $this->start('script'); ?>
<script type="text/javascript">
$(document).ready(function () {
var options, a;
jQuery(function() {
options = {
serviceUrl: "<?php echo $this->Html->Url(array('Controller' => 'Logs', 'action' => 'autoComplete')); ?>",
minChars: 2,
};
a = $('#LogTimeSpent').autocomplete(options);
});
});
$('#saveCust').click(function () {
alert("Test")
});
</script>
<?php $this->end(); ?>
In my controller I have:
function autoComplete($query) {
if ($this->request->is('ajax'))
{
$suggestions = $this->Customer->find('all', array(
'conditions' => array(
'Customer.fullName LIKE' => '%'.$query.'%'
)
));
return json_encode(array('query' => $query, 'suggestions' => $suggestions));
}
}
Customer.fullName is a virtual field if that affects the query. Firebug is currently giving me a 500 internal server error.
Upvotes: 1
Views: 2160
Reputation: 2011
I found out you have to do something special for virtual fields to work. I decided that a virtual field isn't the way to go so I got that updated. The $query
as a parameter is also incorrect, and that I needed to get the querystring from $this->params['url']['query'];
instead. Finally, rather than returning json_encode
I needed to use _serialize
. Here is my updated Controller, so hopefully this will help somebody out. My view is correct in the original post.
function autoComplete() {
if ($this->request->is('ajax'))
{
$query = $this->params['url']['query'];
$this->set('query', $query);
$customer = $this->Log->Customer->find('all', array(
'conditions' => array(
'OR' => array(
'Customer.first_name LIKE' => '%'.$query.'%',
'Customer.last_name LIKE' => '%'.$query .'%'
)),
'fields' => array(
'Customer.first_name', 'Customer.last_name'
)
));
$names = array();
$id = array();
foreach ($customer as $cust) {
$fullName = $cust['Customer']['last_name'] . ', ' . $cust['Customer']['first_name'];
array_push($names, $fullName);
array_push($id, $cust['Customer']['id']);
}
$this->set('suggestions', $names);
$this->set('data', $id);
$this->set('_serialize', array('query', 'suggestions', 'data'));
}
}
Upvotes: 3