yii2依赖自动完成小部件

时间:2014-11-19 19:53:55

标签: jquery autocomplete widget yii2

我在表单中有两个字段:

<?= $form->field($model, 'bill_country')->widget(AutoComplete::className(), ['options' => ['class' => 'form-control'], 'clientOptions' => ['source' => $country_name]])->label('Country') ?>
<?= $form->field($model, 'bill_zip')->widget(AutoComplete::className(), ['options' => ['class' => 'form-control'], 'clientOptions' => ['source' => '/city/list/+id']])->label('Zip') ?>

根据第一个块的选择,我想改变第二个块的'source'。 + id是一个javascript变量... 所以我想用val()获取第一个自动完成的值,将它分配给var id,然后将这个id传递给第二个的源。 我能这样做吗? 或者我应该使用其他选项吗?

谢谢!

2 个答案:

答案 0 :(得分:3)

所以,代码:

$this->registerJs("
    var country = '';
    $('#partner-bill_country').autocomplete({
        select: function( event, ui ) {
            country = (ui.item.country_id);
            $('#partner-bill_zip').autocomplete({
                source: '/city/list/'+country
            });
        }
    });
$('#partner-bill_zip').autocomplete({
    select: function(event, ui) {
        $('#partner-bill_city').val(ui.item.citname);
    }
});
", View::POS_READY, 'partner_script');
//initial arrays:
$city_zip = frontend\models\City::find()
    ->select(['CONCAT(cit_zip, " ", cit_name) as label', 'cit_zip as value', 'cit_id as id', 'cit_name as citname'])
    ->asArray()
    ->all();

$country_name = frontend\models\Country::find()
    ->select(['CONCAT(country_code, " ", country_name) as label', 'country_name as value','id as country_id'])
    ->asArray()
    ->all();
?>
<div class="partner-form">
    <?php $form = ActiveForm::begin(); ?>
        <div class="row">
            <div class="col-lg-6">
                  <?= $form->field($model, 'bill_country')->widget(AutoComplete::className(), ['options' => ['class' => 'form-control'], 'clientOptions' => ['source' => $country_name]])->label('Country') ?>
                  <?= $form->field($model, 'bill_zip')->widget(AutoComplete::className(), ['options' => ['class' => 'form-control'], 'clientOptions' => ['source' => $city_name]])->label('Zip') ?>

答案 1 :(得分:1)

你可以,但Yii2与它无关。你在页面上这样做,在浏览器中,它是一个javascript问题。查看页面,您将看到由Yii和小部件创建的代码,您不应使用自动自动完成,而是创建自己的代码以执行您想要的操作。