by prettyscripts on 2010-11-13 16:38:00
note: CAutoComplete is deprecated as of V113 and replaced with CJuiAutoComplete. Please refer to this post.
yii framework comes with CAutoComplete widget for this purpose. however by default, the displayed value is saved to the database.
thankfully there's tutorial to show how to display one value but save the id to the database. codes documented post is based on the tutorial, with some modification to suit my own needs.
in controller file, add a new action:
PHP:
function actionAutocomplete() { | |
if (Yii::app()->request->isAjaxRequest && isset($_GET['q'])) { | |
$data = lookup_function($_GET['q']); | |
$results = array(); | |
foreach ($data as $id => $value) { | |
$results[] = $id . '|' . $value; | |
} | |
echo implode("\n", $results); | |
} | |
} |
PHP:
<?php $this->widget('CAutoComplete', array( | |
'name' => 'data_name', | |
'value' => isset($model->data_id) ? $model->Data->name : '', | |
'url' => $this->createUrl('/path/to/controller/autocomplete'), | |
'htmlOptions' => array('size' => '30'), | |
'methodChain' => ".result(function(event, item) {\$(\"#<controller_name>_data_id\").val(item[1]); })", | |
)) ?> | |
<?php echo $form->hiddenField($model, 'data_id'); ?> |
Tags: ajax, autocomplete, php, save, yii