CJuiAutoComplete 封裝 jQuery UI Autocomplete,提供輸入建議下拉選單,支援本地陣列、AJAX 遠端資料源與自訂模板。
<?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name' => 'city',
'source' => $data, // 控制器傳入的陣列
'options' => array(
'minLength' => 2, // 至少輸入 2 字元觸發
'delay' => 300, // 延遲毫秒
'autoFocus' => true, // 自動聚焦第一項
),
'htmlOptions' => array(
'style' => 'height:20px;',
'placeholder' => '輸入城市名稱...',
),
)); ?>
public function actionIndex() {
$data = array('Nanjing', 'Beijing', 'Perth', 'Chicago', 'Paris', 'Pengnai', 'Sydney');
$this->render('index', array('data' => $data));
}
'source' => 'js:function(request, response) {
$.getJSON("'.Yii::app()->createUrl('site/suggestCity').'", { term: request.term }, response);
}',
控制器回傳 JSON 陣列:
public function actionSuggestCity() {
if (Yii::app()->request->isAjaxRequest) {
$term = $_GET['term'];
$cities = City::model()->findAll(array(
'condition' => 'name LIKE :term',
'params' => array(':term' => "%$term%"),
'limit' => 10,
));
echo CJSON::encode(array_map(function($c) { return $c->name; }, $cities));
Yii::app()->end();
}
}
'options' => array(
'minLength' => 1,
'_renderItem' => 'js:function(ul, item) {
return $("").append("" + item.label + "
" + item.desc + "").appendTo(ul);
}',
),
資料源需回傳物件陣列:[{label:'Taipei', desc:'台灣首都'}, ...]
<?php $form=$this->beginWidget('CActiveForm'); ?>
<?php echo $form->labelEx($model,'city'); ?>
<?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'model' => $model,
'attribute' => 'city',
'source' => $data,
)); ?>
<?php echo $form->error($model,'city'); ?>
<?php $this->endWidget(); ?>
minLength、資料源格式、jQuery UI CSS 是否載入'delay' => 500 避免拼音過程觸發