首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Yii Framework CJuiAutoComplete 自動完成輸入框元件完整教學

     編輯:PHP 綜合知識

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));
}

進階:AJAX 遠端資料源

'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();
    }
}

自訂顯示模板(需 jQuery UI 1.9+)

'options' => array(
    'minLength' => 1,
    '_renderItem' => 'js:function(ul, item) {
        return $("
  • ").append("" + item.label + "
    " + item.desc + "
    ").appendTo(ul); }', ),
  • 資料源需回傳物件陣列:[{label:'Taipei', desc:'台灣首都'}, ...]

    表單整合:CActiveForm 搭配

    <?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 避免拼音過程觸發
    • 表單送出驗證:AutoComplete 只是 UI 輔助,後端仍需驗證輸入值合法性
    1. 上一篇文章:
    2. 下一篇文章:
    Copyright © 程式碼之家 All Rights Reserved