I am new to yii. I need to write custom yii auto complete.I knew that CJuiAutocomplete is there.but I need to implement own custom auto complete. can anyone pls guide me or help me to develop custom autocomplete textfield. taking the id while displaying name in the textfield.
Thanks in advance
Here is an action in site controller...
public function actionAutoComplete($term){
$query = Yourmodel::model()->findallbyattributes( array('somecolumn'=>$term));
$list = array();
foreach($query as $q){
$data['value']= $q['id'];
$data['label']= $q['name'];
$list[]= $data;
unset($data);
}
echo json_encode($list);
}
and here is a search form in your view:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'searchform',
'enableAjaxValidation'=>false,
'action' => '/'
)); ?>
<fieldset>
<div class="input-append">
<?php
echo CHtml::hiddenField('selectedvalue','');
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name'=>'searchbox',
'value'=>'',
'source'=>CController::createUrl('/site/autoComplete'),
'options'=>array(
'showAnim'=>'fold',
'minLength'=>'2',
'select'=>'js:function( event, ui ) {
$("#searchbox").val( ui.item.label );
$("#selectedvalue").val( ui.item.value );
return false;
}',
),
'htmlOptions'=>array(
'onfocus' => 'js: this.value = null; $("#searchbox").val(null); $("#selectedvalue").val(null);',
'class' => 'input-xxlarge search-query',
'placeholder' => "Search...",
),
));
echo '<button class="btn" type="submit">Submit</button>';
?>
</div>
</fieldset>
<?php $this->endWidget(); ?>
</form>
Because of this condition
array('somecolumn'=>$term)
it will show results only if you write full string. For example, you have ['coffee', 'cake']. When you type in search box it wont show results for coff, cof, co, ca, cak etc. only will show results if you enter full word coffee, you will get ['coffee'] as result.
So you need something like:
$match = $_GET['term'];
$tags = Tags::model()->findAll(
'tag_name LIKE :match',
array(':match' => "%$match%")
);
This will show results for coff, cof, co, ca, cak etc.