我正在努力创建带有自动完成字段(Customer
)的表单。因此,当用户在此字段中键入一些字母时,运行查询将返回name
,surname
或company
字段中包含这些字母的所有客户,并且用户可以选择一个来完成表格。
这是客户的表单字段:
add.ctp
echo $this->Form->control('customer', ['id' => 'Autocomplete', 'empty' => true]);
这是Js函数:
<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
这是包含查询的getAll函数:
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);
}
但是我没有任何结果...