In the Yii2 advanced app in the Signup form,
I would like the street and city to show up, when a postcode is typed and the postcode field looses focus.
To the user table was added: postcode(Varchar(6)) (In the Netherlands the postcode fomat is like 3743DA or 3743 DA)
3 tables are added:
street: id, street
city: id, city
postcode: id, postcode, street_id, city_id
In my common/models/Postcode model
public function getCity()
{
return $this->hasOne(City::className(), ['id' => 'city_id']);
}
public function getStreet()
{
return $this->hasOne(Street::className(), ['id' => 'street_id']);
}
in common/models/RecordHelpers.php
Uses were added
use common\models\Postcode;
use common\models\Street;
use common\models\City;
and a function for retreiving street and city was added.
public function getStreetCity($postcode="3741DA") {
$postcode = str_replace(' ', '', strtoupper($postcode));
$sql = 'SELECT `street`, `city` '
. 'FROM postcode, street, city '
. 'WHERE postcode="'.$postcode.'" '
. 'AND postcode.street_id = street.id '
. 'AND postcode.city_id=city.id ';
$address = Postcode::findBySql($sql)->one();
}
in frontend/views/site/signup.php
Javascript code was added: (when the focus of the postcode field is lost replace div id Address with street and city.)
$this->registerJs('$("#signupform-postcode").blur(function() {
if ($(this).val().length==6 || $(this).val().length==7){
$("#address").text("Street and City here");}
});');
underneath the postcode field I’ve placed the address div.
<?= $form->field($model, 'postcode') ?>
<div id="address"></div>
Now the question is how to lookup street and city and place them in address div…