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