how to create custom autocomplete textfield in yii

橙三吉。 提交于 2019-12-20 03:09:26

问题


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


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/14197669/how-to-create-custom-autocomplete-textfield-in-yii

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!