问题
I have two fields in a form:
<?= $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') ?>
Based on the selection of the first block, I want to change the 'source' of the second one. +id is a javascript variable... So I vant to get the value of the first autocomplete with val(), assign it to var id, and then pass this id to the source of the second. Can I do that? Or should I use another option?
Thanks!
回答1:
You can but Yii2 has nothing to do with it. You are doing this on page, in the browser, it is a javascript issue. Look at the page and you will see the code that gets created by Yii and the widgets, you should not use the automatic autocomplete but create your own code to do what you want.
回答2:
So, the code:
$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') ?>
来源:https://stackoverflow.com/questions/27025791/yii2-dependent-autocomplete-widget