Yii2 - 使用自动完成输入搜索

时间:2015-11-11 12:59:56

标签: jquery-ui yii autocomplete yii2

我使用默认的Yii2 library for auto-complete。我怎样才能创建它,所以它是在用户输入时从DB读取值?

这是我到目前为止的代码,但查询是在创建页面时完成的:

echo AutoComplete::widget([
                'name' => 'tradeName',
                'model' => TradeNames::find()->select('name')->all(),
                'options' => [
                    'class' => 'form-control'
                ],
                'clientOptions' => [
                        'source' => array_column(TradeNames::find()->select('name')->asArray()->all(), 'name'),

                        },
                    ],
            ]);

2 个答案:

答案 0 :(得分:1)

我遵循了这个建议 jqueryui.com/autocomplete/#multiple并编写了下一个代码

<div id="autocomplete" class="ui-widget">
    <?= \yii\jui\AutoComplete::widget([
        'attribute' => 'attribute',
        'name' => 'tradeName',
        'clientOptions' => [
            'source' => \Yii::$container->get('JsExpression',['function(request, response) {
                  response( $.ui.autocomplete.filter( window.dataAsArray, extractLast( request.term ) ) );
            }']),
            'select' => \Yii::$container->get('JsExpression',['function(event, ui) {
                var terms = split( this.value );
                terms.pop();
                terms.push( ui.item.value );
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }']),
            'focus' => \Yii::$container->get('JsExpression',['function() {
                return false;
            }']),
        ]
    ]) ?>
</div>  

<script>
    window.dataAsArray = ['item1', 'item2', 'item3'];
    function split( val ) {
         return val.split( /,\s*/ );
    }

    function extractLast( term ) {
        return split( term ).pop();
    }
    $(document).ready( function() {
        $('#autocomplete').on('keydown', function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) {
                event.preventDefault();
            }
         });
    });
</script>

也许对某人有帮助

答案 1 :(得分:0)

试试这个

use yii\jui\AutoComplete;
use yii\web\JsExpression;

<?php
            $data = TradeNames::find()
            ->select(['name as value', 'name as  label','id as id'])
            ->asArray()
            ->all();

            echo 'Trade Names' .'<br>';
            echo AutoComplete::widget([
                 'name' => 'tradeName',    
                 'id' => 'trade_name',
                 'clientOptions' => [
                    'source' => $data,
                    // 'minLength'=>'3', 
                    'autoFill'=>true,
                    'select' => new JsExpression("function( event, ui ) {
                    $('#memberssearch-family_name_id').val(ui.item.id);//#memberssearch-family_name_id is the id of hiddenInput.
                 }")],
                 ]);
            ?>


 <?= Html::activeHiddenInput($model, 'tradeName')?>