by prettyscripts on 2012-01-20 14:17:00
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.
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:
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:
Tags: ajax, autocomplete, jquery, php, yii