Hi guys,
following code did it’s job for a long time, but now, it will do nothing any more. Netiher any error in debugger nor anything else. What happened with this framework?
Here is JS code:
<?php
$url = Url::to(['plz/get-city-province']);
$script = <<< JS
$('#zip_code').change(function(){
alert('Try to change plz...');
var zipId=$(this).val();
$.get('$url',{zipId:zipId},function(data){
//var data=$.parseJSON(data);
alert(data.plz+" entspricht der Stadt "+data.ort+"! Die Id ist "+zipId);
$('#immobilien-stadt').attr('value',data.ort);
});
});
JS;
$this->registerJS($script);
?>
Here is View:
<div class="col-md-4">
<?php
$route = Url::to(['auswahlk']);
?><?=
$form->field($model, 'l_plz_id', ['addon' => [
'prepend' => ['content' => 'Plz']]])->widget(\kartik\widgets\Select2::classname(), [
'options' => ['placeholder' => Yii::t('app', 'Postleitzahl wählen'),
'id' => 'zip_code',
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => $route,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function(markup) { return markup; }'),
'templateResult' => new JsExpression('function(bewerber) { return bewerber.text; }'),
'templateSelection' => new JsExpression('function(bewerber) { return bewerber.text; }'),
],
])->label(false);
?>
</div>
Here is Controler, both in Kundencontroller and in PlzController:
public function actionAuswahlk($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new yii\db\Query();
$query->select('id, plz AS text')
->from('l_plz')
->where(['like', 'plz', $q]);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
} elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => LPlz::find($id)->plz];
}
return $out;
}
public function actionGetCityProvince($zipId) {
$location = LPlz::findOne($zipId);
return Json::encode($location);
}