[moka同学笔记]Yii下国家省市三级联动

第一次做省市三级联动时候遇到了坑,感觉还是自己太菜。头疼了很久研究了很久,最后终于发现了问题。大致总结一下思路

在控制器中实例化model,然后在视图中渲染所有国家,当选取国家时候,ajax通过 id="community-country_id" 把country_id传递到控制器中,控制器通过$this->ajaxGetProvince(); 得到country_id相同的省,再在视图中渲染显示该国家下省,选取省后,ajax再通过id="community-province_id" 传递province_id到控制器,控制器通过 $this->ajaxGetCity();得到province_id相同的市,再在视图中显示该省下的城市。

1.在视图中时候

第一种:(因为是地区管理库,国家表,省表,城市表三者分开,而非同一张表)

<div class="form-group field-community-country_id required">
  <label class="col-lg-1 control-label" for="community-country_id">地区</label>
  <div class="col-lg-8">
    <?php
    $countryList = array();
    $countryList = ArrayHelper::map(CountryRegion::find()->where([‘is_deleted‘=>0])->orderBy([‘order_num‘=>SORT_ASC,‘id‘=>SORT_ASC])->all(), ‘id‘, ‘name‘);
    ?>
    <select id="community-country_id" class="form-control" name="Community[country_id]" style="width:200px;display: inline-block">
      <option value="" selected>请选择</option>
      <?php foreach ($countryList as $key => $val): ?>
        <option value="<?= $key ?>" <?= $modelCommunity->country_id != null && $modelCommunity->country_id == $key ? ‘ selected ‘ : ‘‘ ?>><?= $val ?></option>
      <?php endforeach; ?>
    </select>

    <?php
    $provinceList = array();
    if ($modelCommunity->country_id) {
      $provinceList = ArrayHelper::map(Province::find()->where([‘country_id‘ => $modelCommunity->country_id,‘is_deleted‘=>0])->orderBy([‘order_num‘=>SORT_ASC,‘id‘=>SORT_ASC])->all(), ‘id‘, ‘name‘);
    }
    ?>
    <select id="community-province_id" class="form-control" name="Community[province_id]" style="width:200px;display: inline-block">
      <option value="">请选择</option>
      <?php foreach ($provinceList as $key => $val): ?>
        <option value="<?= $key ?>"    <?= $modelCommunity->province_id != null && $modelCommunity->province_id == $key ? ‘ selected ‘ : ‘‘ ?>><?= $val ?></option>
      <?php endforeach; ?>
    </select>

    <?php
    $cityList = array();
    if ($modelCommunity->province_id) {
      $cityList = ArrayHelper::map(City::find()->where([‘province_id‘ => $modelCommunity->province_id,‘is_deleted‘=>0])->orderBy([‘order_num‘=>SORT_ASC,‘id‘=>SORT_ASC])->all(), ‘id‘, ‘name‘);
    }
    ?>
    <select id="community-city_id" class="form-control" name="Community[city_id]" style="width:200px;display: inline-block">
      <option value="">请选择</option>
      <?php foreach ($cityList as $key => $val): ?>
        <option value="<?= $key ?>"<?= $modelCommunity->city_id != null && $modelCommunity->city_id == $key ? ‘ selected ‘ : ‘‘ ?>><?= $val ?></option>
      <?php endforeach; ?>
    </select>
  </div>
</div>

第二种:(在做学校管理,国家,省,城市,三者都在school表中)

<div class="form-group field-community-country_id required">
    <label class="col-lg-1 control-label" for="community-country_id">地区</label>
    <div class="col-lg-8">
        <?php
        $countryList = array();
        $countryList = ArrayHelper::map(CountryRegion::find()->where([‘is_deleted‘ => 0])->orderBy([‘order_num‘ => SORT_ASC, ‘id‘ => SORT_ASC])->all(), ‘id‘, ‘name‘);
        ?>
        <select id="community-country_id" class="form-control" name="School[country_id]"
                style="width:200px;display: inline-block">
            <option value="" selected>请选择</option>
            <?php foreach ($countryList as $key => $val): ?>
                <option
                    value="<?= $key ?>" <?= $model->country_id != null && $model->country_id == $key ? ‘ selected ‘ : ‘‘ ?>><?= $val ?></option>
            <?php endforeach; ?>
        </select>

        <?php
        $provinceList = array();
        if ($model->country_id) {
            $provinceList = ArrayHelper::map(Province::find()->where([‘country_id‘ => $model->country_id, ‘is_deleted‘ => 0])->orderBy([‘order_num‘ => SORT_ASC, ‘id‘ => SORT_ASC])->all(), ‘id‘, ‘name‘);
        }
        ?>
        <select id="community-province_id" class="form-control" name="School[province_id]"
                style="width:200px;display: inline-block">
            <option value="">请选择</option>
            <?php foreach ($provinceList as $key => $val): ?>
                <option
                    value="<?= $key ?>"<?= $model->province_id != null && $model->province_id == $key ? ‘ selected ‘ : ‘‘ ?>><?= $val ?></option>
            <?php endforeach; ?>
        </select>

        <?php
        $cityList = array();
        if ($model->province_id) {
            $cityList = ArrayHelper::map(City::find()->where([‘province_id‘ => $model->province_id, ‘is_deleted‘ => 0])->orderBy([‘order_num‘ => SORT_ASC, ‘id‘ => SORT_ASC])->all(), ‘id‘, ‘name‘);
        }
        ?>
        <select id="community-city_id" class="form-control" name="School[city_id]"
                style="width:200px;display: inline-block">
            <option value="">请选择</option>
            <?php foreach ($cityList as $key => $val): ?>
                <option
                    value="<?= $key ?>"<?= $model->city_id != null && $model->city_id == $key ? ‘ selected ‘ : ‘‘ ?>><?= $val ?></option>
            <?php endforeach; ?>
        </select>
    </div>
</div>

第三种:(只有省和市联动,国家是中国)

<?php
$provinceList = ArrayHelper::map(Province::find()->where([‘country_id‘ => 142])->all(), ‘id‘, ‘name‘);
?>
<?= $form->field($model, ‘province_id‘)->dropDownList($provinceList, [‘prompt‘ => ‘请选择‘, ‘style‘ => ‘width:200px‘,‘id‘=>‘community-province_id‘]) ?>
<?php
$cityList = array();
if ($model->province_id) {
    $cityList = ArrayHelper::map(City::find()->where([‘province_id‘ => $model->province_id])->all(), ‘id‘, ‘name‘);
}
?>
<?= $form->field($model, ‘city_id‘)->dropDownList($cityList, [‘prompt‘ => ‘请选择‘, ‘style‘ => ‘width:200px‘,‘id‘=>‘community-city_id‘]) ?>

2.在控制器中

第一种:

 //添加地区
    public function actionCreate(){

        $this->ajaxGetProvince(); //用作城市联动       这段很重要,因为需要获取前台传递过来的country_id,所以不能丢

        $CountryModel = new CountryRegion();
        $ProvinceModel = new Province();
        $CityModel = new City();
        $CityProvince = new Province();

      /**其他代码*/

        return $this->render(‘create‘,[
            ‘level‘=>$level,
            ‘CountryModel‘=>$CountryModel,
            ‘ProvinceModel‘=>$ProvinceModel,
            ‘CityModel‘=>$CityModel,
            ‘CityProvince‘=>$CityProvince
        ]);
    }

第二种和第三种控制器中一样代码如下:


public function actionCreate(){    $this->ajaxGetProvince(); //用作城市联动    $this->ajaxGetCity(); //用作城市联动

 $model = new School();

     /**中间其他代码*/
  return $this->render(‘create‘, [    ‘model‘ => $model,]);
 

3.前端

/*国家、省份联动ActiveRecord*/
$(document).on(‘change‘, ‘#community-country_id‘, function () {
    var $select = $(this),
        requestUrl = $select.attr(‘data-country-url‘) || window.location.href;
    if ($select.attr(‘data-requestform‘) === ‘true‘) {
        requestUrl = $select.parents(‘form‘).attr(‘action‘);
    }
    $(‘#community-province_id‘).html(‘<option value="">请选择</option>‘);
    $(‘#community-city_id‘).html(‘<option value="">请选择</option>‘);
    if ($select.val()) {
        $.ajax({
            url: requestUrl,
            data: {
                country_id: $select.val(),
                ajax_get_province: true
            },
            type: "GET",
            success: function (e) {
                $(‘#community-province_id‘).html(e);
                $(‘#community-city_id‘).html(‘<option value="">请选择</option>‘);
                console.log(e);
            }
        });
    }
});

/*省份、城市联动ActiveRecord*/
$(document).on(‘change‘, ‘#community-province_id‘, function () {
    var $select = $(this),
        requestUrl = $select.attr(‘data-province-url‘) || window.location.href;
    if ($select.attr(‘data-requestform‘) === ‘true‘) {
        requestUrl = $select.parents(‘form‘).attr(‘action‘);
    }

    $(‘#community-city_id‘).html(‘<option value="">请选择</option>‘);
    if ($select.val()) {
        $.ajax({
            url: requestUrl,
            data: {
                province_id: $select.val(),
                ajax_get_city: true
            },
            type: "GET",
            success: function (e) {
                $(‘#community-city_id‘).html(e);
                console.log(e);
            }
        });
    }
});

以上~~

第一次这样做,应该会有更简单的方法吧,请求高手指导。

转载本文请注明出处。

时间: 2024-10-13 16:16:27

[moka同学笔记]Yii下国家省市三级联动的相关文章

[moka同学笔记]window下.htacess文件 与linux下.htacess文件

windows下 # Turn on URL rewritingRewriteEngine On # Installation directoryRewriteBase / # Protect hidden files from being viewed<Files .*>    Order Deny,Allow    Deny From All</Files> # Protect application and system files from being viewedRewr

[moka同学笔记]yii2.0小物件的简单使用(第二种方法)

1.在widgets/TestWidget.php中 1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: moka同学 5 * Date: 2016/08/05 6 * Time: 18:15 7 */ 8 namespace app\widgets; 9 10 use yii\base\Widget; 11 12 class TestWidget extends Widget 13 { 14 public $msg = ''; 15 16 //初始

[moka同学笔记]redis练习Demo

<?php /** * Created by PhpStorm. * User: moka同学 * Date: 2017/3/13 * Time: 10:54 */ echo 'Hello redis'.'<br>'; $redis = new Redis(); $redis->connect("127.0.0.1","6379"); //demo1 /*$redis->set("name","This i

省市三级联动

mumuy-widget-91839b8 http://jquerywidget.com/ /** * jquery.citys.js 1.0 * http://jquerywidget.com */ ;(function (factory) { if (typeof define === "function" && (define.amd || define.cmd) && !jQuery) { // AMD或CMD define([ "jq

Webform——中国省市三级联动以及IsPostBack

首先要明白Webform的运行顺序,当开始启动时候,首先执行的是Page_Load事件, 当点击任意按钮后,每次点击都要先执行一遍Page_Load(在这里Page_Load里面的事件是给数据控件加载数据)事件,然后才执行按钮上的内容. 但是如果是一个数据控件,里面存的是一些数据,如果用foreach遍历逐项给数据控件添数据的话,每次点击按钮(即刷新页面)都会执行一遍Page_Load,也就是说每次都要重复添加原来的数据,所以这就需要一个判断条件,使它只会第一次启动的时候走Page_Load事件

[moka同学笔记]yii2.0的下拉菜单与bootstrap下拉菜单

1.yii2下拉菜单 1 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">管理<b class="caret"></b></a> 2 <ul class="dropdown-menu"> 3 <li&

[moka同学笔记转载]Yii 设置 flash消息 创建一个渐隐形式的消息框

来源:http://www.cnblogs.com/xp796/p/5481004.html Yii 设置 flash消息 创建一个渐隐形式的消息框 1 /*适用情况:比如提交一个表单,提交完成之后在页面展示一条提示消息. 2 控制器里面这样写: 3 单条消息: 4 */ 5 \Yii::$app->getSession()->setFlash('error', 'This is the message'); 6 7 \Yii::$app->getSession()->setFla

[moka同学笔记]yii2场景的使用(摘录)

前半部分为自己使用的过程,下边为转载的,具体地址见:http://blog.sina.com.cn/s/blog_88a65c1b0101j717.html 1.在model中 public function rules() { return [ [['join_verify', 'create_activity', 'is_open_group', 'is_open_child_com','sendmail_limit','sendmail_from_name','sendmail_from'

[moka同学笔记]Yii2 自定义class、自定义全局函数(摘录)

1.在app\components下新建MyComponent.PHP namespace app\components; use Yii; use yii\base\Component; use yii\base\InvalidConfigException; class MyComponent extends Component { public function welcome() { echo "Hello..Welcome to MyComponent"; } } 2.在co