Yii CJuiAutoComplete

本文介绍如何使用Yii框架中的CJuiAutoComplete组件实现自动完成功能。包括了配置示例代码及控制器中处理自动完成请求的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

i have previously written a post on the same topic with CAutoComplete. since CAutoComplete is deprecated (since V113) and replaced with CJuiAutoComplete, i should keep my notes up-to-dated.

i find that CJuiAutoComplete is easier to implement. the following is based on a this forum post.
view file or the form

PHP <?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'model' => $model,
'attritube' => 'name_of_attribute',
'name' => 'name_of_field',
'value' => 'default_display_value',
'source' => createUrl('/path/to/controller/autocomplete'),
'options' => array(
'minLength' => 2,
'select' => "js:function(event, ui) {
$('#<field_id>').val(ui.item.['<id>']);
}",
'change' => "js:function(event, ui) {
if (!ui.item) {
$('#<field_id>').val('');
}
}",
),
)) ?>


notes:
line 4: do not use codes line 2-3 this field is for display a value. ensure there's a hidden field on the form to be saved to the database.
lines 9 - 15: optional. for situation such as to display value on a field but save the id to database.
line 10: eg set hidden field with the actual data value to be saved to database, see next section regarding <id>
lines 12 - 15: clear field value if data is empty
autocomplete action

in controller file, add a new action:


PHP function actionAutocomplete() {
if (Yii::app()->request->isAjaxRequest && isset($_GET['term'])) {
$models = Model::model()->getData($_GET['term']);
$result = array();
foreach ($models as $m)
$result[] = array(
'label' => $m->attribute_displayed_in_drop down_list,
'value' => $m->attribute_for_input_field,
'id' => $m->attribute_for_hidden_field_or_to_be_saved,
'field' => $m->attribute_for_another_field,
);

echo CJSON::encode($result);
}


notes:
line 7: can be formatted string to be displayed on the drop down list.
line 8: value to be displayed in current input field
line 9-10: optional. values to be set on another field on the same form. refering to line 8 above. can be accessed as array.

© prettyscripts. like this article? please rate and subscribe!
Tags: ajax, autocomplete, jquery, php, yii
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值