Yii Framework Forum

Load data from external source to fill form fields via dropdownlist


(Demayrizelly) #1

I have a 2 tables…customers and location. customers table have customer_id, customer_name, zip_code, city and province.

Location table have location_id, zip_code, city, and province.

location table is filled with data.

What I want to achieve is autopopulate customer’s city and province fields when zipcode is selected from a dropdownlist

I have the below codes but it ain’t working and any help is appreciated

customer form

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use backend\models\Location;

/* @var $this yii\web\View */
/* @var $model backend\models\Customers */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="customers-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'customer_name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'zip_code')->dropDownList(ArrayHelper::map(Location::find()->all(), 'location_id', 'zip_code'),['prompt'=>'Select location', 'id'=>'customers-zip_code']) ?>

    <?= $form->field($model, 'city')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'province')->textInput(['maxlength' => true]) ?>

    <div class="form-group">
        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

<?php
$script = <<< JS

$('#customers-zip_code').change(function(){
	var zipId = $(this).val();
	alert();
	
	$.get('index.php?r = location/get-city-province',{ zipId: zipId },funtion(data){
		var data = $.parseJSON(data);
		$('#customers-city').attr('value',data.city);
		$('#customers-province').attr('value',data.province);
	});
});
JS;
$this->registerJs($script);
?>

Controller’s new method to get the data
.
.
.
.
public function actionGetCityProvince($zipId)
{
$locations = Location::findOne($zipId);
echo Json::encode($locations);
}

.
.
.
.
.
.
.