Yii2使用dropdownlist实现地区三级联动功能的方法


Posted in PHP onJuly 18, 2016

本文实例讲述了Yii2使用dropdownlist实现地区三级联动功能的方法。分享给大家供大家参考,具体如下:

视图部分:

<?php
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\search\service\ItemSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="row">
  <div class="item-search">
    <?php $form = ActiveForm::begin([
      'action' => ['index'],
      'method' => 'get',
      'options' => ['class' => 'form-inline']
    ]); ?>
    <?= $form->field($model, 'cityName', ['options' => ['class' => 'form-group col-lg-2']])->dropDownList(ArrayHelper::map($cities, 'id', 'name'), ['prompt' => '请选择城市'])->label('请选择城市', ['class' => 'sr-only']) ?>
    <?= $form->field($model, 'areaName', ['options' => ['class' => 'form-group col-lg-2']])->dropDownList(ArrayHelper::map($areas, 'id', 'name'), ['prompt' => '请选择区县'])->label('请选择区县', ['class' => 'sr-only']) ?>
    <?= $form->field($model, 'communityName', ['options' => ['class' => 'form-group col-lg-2']])->dropDownList(ArrayHelper::map($communities, 'id', 'name'), ['prompt' => '请选择小区'])->label('请选择小区', ['class' => 'sr-only']) ?>
    <div class="col-lg-2 col-lg-offset-1">
      <input class="form-control" id="keyword" placeholder="请输入小区名" value="" />
    </div>
    <div class="col-lg-1">
      <button type="button" id="search-community" class="btn btn-info">搜索</button>
    </div>
    <p></p>
    <div class="form-group col-lg-1 pull-right">
      <?= Html::submitButton('搜索', ['class' => 'btn btn-primary']) ?>
    </div>
    <?php ActiveForm::end(); ?>
  </div>
</div>
<p> </p>
<?php
$this->registerJs('
  //市地址改变
  $("#itemsearch-cityname").change(function() {
    //市id值
    var cityid = $(this).val();
    $("#itemsearch-areaname").html("<option value=\"0\">请选择区县</option>");
    $("#itemsearch-communityname").html("<option value=\"0\">请选择小区</option>");
    if (cityid > 0) {
      getArea(cityid);
    }
  });
  //区地址改变
  $("#itemsearch-areaname").change(function() {
    //区id值
    var areaid = $(this).val();
    $("#itemsearch-communityname").html("<option value=\"0\">请选择小区</option>");
    if (areaid > 0) {
      getCommunity(areaid);
    }
  });
  //获取市下面的区列表
  function getArea(id)
  {
    var href = "' . Url::to(['/service/base/get-area-list'], true). '";
    $.ajax({
      "type" : "GET",
      "url"  : href,
      "data" : {id : id},
      success : function(d) {
        $("#itemsearch-areaname").append(d);
      }
    });
  }
  //获取区下面的小区列表
  function getCommunity(id)
  {
    var href = "' . Url::to(['/service/base/get-community-list'], true) . '";
    $.ajax({
      "type" : "GET",
      "url"  : href,
      "data" : {id : id},
      success : function(d) {
        $("#itemsearch-communityname").append(d);
      }
    });
  }
  //搜索小区
  $("#search-community").click(function() {
    var word  = $("#keyword").val();
    var areaid = $("#itemsearch-areaname option:selected").val();
    var href  = "' . Url::to(['/service/base/search-community'], true) . '";
    if (areaid > 0) {
      $.ajax({
        "type" : "GET",
        "url"  : href,
        "data" : {id : areaid, word : word},
        success : function(d) {
          $("#itemsearch-communityname").html(d);
        }
      });
    }
  });
');
?>

模型部分:

就是我们常用的ajax请求,当然php中需要直接组合成<option value=""></option>这样的结构直接用,$form->field($model, $var)中的变量数据表中不一定有,得在模型中自己定义,并设置安全字段,而且搜索模型也可能需要修改成自己需要的样子,模型可能要这样:

class HuangYeError extends \yii\db\ActiveRecord
{
  public $cityName;
  public $areaName;
  public $communityName;
  public $group;
  public $cate;
  /**
   * @inheritdoc
   */
  public static function tableName()
  {
    return 'll_hy_huangye_error';
  }
  public static function getDb()
  {
    return Yii::$app->get('dbnhuangye');
  }
}

之前是多表,需要使用jjoinWith()连表,后来被我全部转化为单表了,多表实在是慢,能转化成单表就用单表吧:

class HuangYeErrorSearch extends HuangYeError
{
  const PAGE_SIZE = 20;
  public $communityName;
  public $startTime;
  public $endTime;
  /**
   * @inheritdoc
   */
  public function rules()
  {
    return [
      [['id', 'serviceid', 'userid', 'categoryid', 'communityid', 'sortorder', 'ctime', 'utime', 'status'], 'integer'],
      [['username', 'name', 'logo', 'phone', 'address', 'content', 'error', 'communityName', 'startTime', 'endTime'], 'safe'],
    ];
  }
  /**
   * @inheritdoc
   */
  public function scenarios()
  {
    // bypass scenarios() implementation in the parent class
    return Model::scenarios();
  }
  /**
   * Creates data provider instance with search query applied
   *
   * @param array $params
   *
   * @return ActiveDataProvider
   */
  public function search($params)
  {
    $query = HuangYeError::find();
    //status == 9 删除状态
    $condition = ' `status` != :status';
    $p[':status'] = 9;
    $query->where($condition, $p);
    $dataProvider = new ActiveDataProvider([
      'query' => $query,
      'pagination' => [
        'pageSize' => self::PAGE_SIZE,
      ],
    ]);
    $this->load($params);
    if (!$this->validate()) {
      // uncomment the following line if you do not want to any records when validation fails
      // $query->where('0=1');
      return $dataProvider;
    }
    $query->andFilterWhere([
      'userid' => $this->userid
    ]);
    $query->andFilterWhere(['like', 'username', $this->username])
      ->andFilterWhere(['like', 'name', $this->name])
      ->andFilterWhere(['like', 'phone', $this->phone])
      ->andFilterWhere(['like', 'address', $this->address])
      ->andFilterWhere(['like', 'content', $this->content])
      ->andFilterWhere(['ll_hy_huangye_error.status' => $this->status])
      ->andFilterWhere(['ll_hy_huangye_error.categoryid' => $this->categoryid])
      ->andFilterWhere(['between', 'ctime', strtotime($this->startTime . '0:0:0'), strtotime($this->endTime . '23:59:59')])
      ->andFilterWhere(['like', 'error', $this->error]);
    if (intval($this->communityName)) {
      $query->andFilterWhere(['ll_hy_huangye_error.communityid' => intval($this->communityName)]);
    }
    $order = ' `ctime` DESC';
    $query->orderBy($order);
    return $dataProvider;
  }
}

控制器中写比较简单一点,直接调用就行了:

/**
* ajax请求小区
*
* @param $id
* @return string
*/
public function actionGetCommunityList($id)
{
    $option = '';
    $result = self::getCommunity($id);
    if ($result) {
      foreach ($result as $value) {
        $option .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
      }
    } else {
      $option .= '<option value="0">暂未开通可选择的小区</option>';
    }
    echo $option;
}

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

PHP 相关文章推荐
使用PHP socke 向指定页面提交数据
Jul 23 PHP
php 采集书并合成txt格式的实现代码
Mar 01 PHP
第七章 php自定义函数实现代码
Dec 30 PHP
for循环连续求和、九九乘法表代码
Feb 20 PHP
php调用方法mssql_fetch_row、mssql_fetch_array、mssql_fetch_assoc和mssql_fetch_objcect读取数据的区别
Aug 08 PHP
域名和cookie问题(域名后缀)
Oct 10 PHP
php实现用手机关闭计算机(电脑)的方法
Apr 22 PHP
PHP的数组中提高元素查找与元素去重的效率的技巧解析
Mar 03 PHP
Yii调试查看执行SQL语句的方法
Jul 15 PHP
PHP 读取大文件并显示的简单实例(推荐)
Aug 12 PHP
php结合md5的加密解密算法实例
Sep 30 PHP
php封装json通信接口详解及实例
Mar 07 PHP
Yii2框架dropDownList下拉菜单用法实例分析
Jul 18 #PHP
用HTML/JS/PHP方式实现页面延时跳转的简单实例
Jul 18 #PHP
浅谈PHP正则中的捕获组与非捕获组
Jul 18 #PHP
Yii2.0表关联查询实例分析
Jul 18 #PHP
php 实现301重定向跳转实例代码
Jul 18 #PHP
PHP的openssl加密扩展使用小结(推荐)
Jul 18 #PHP
PHP多进程编程总结(推荐)
Jul 18 #PHP
You might like
PHP类中Static方法效率测试代码
2010/10/17 PHP
PHP ? EasyUI DataGrid 资料取的方式介绍
2012/11/07 PHP
Php header()函数语法及使用代码
2013/11/04 PHP
Zend Framework教程之资源(Resources)用法实例详解
2016/03/14 PHP
PHP mysqli_free_result()与mysqli_fetch_array()函数详解
2016/09/21 PHP
PHP设计模式之抽象工厂模式实例分析
2019/03/25 PHP
PHP 命名空间和自动加载原理与用法实例分析
2020/04/29 PHP
js实现的跟随鼠标移动的时钟效果(中英文日期显示)
2011/01/17 Javascript
js动态添加onclick事件可传参数与不传参数
2014/07/29 Javascript
Jquery中Event对象属性小结
2015/02/27 Javascript
jquery实现的仿天猫侧导航tab切换效果
2015/08/24 Javascript
jQuery插件dataTables添加序号列的方法
2016/07/06 Javascript
jQuery动态改变多行文本框高度的方法
2016/09/07 Javascript
jQuery与js实现颜色渐变的方法
2016/12/30 Javascript
Vue.js组件tab实现选项卡切换
2020/03/23 Javascript
Vue的elementUI实现自定义主题方法
2018/02/23 Javascript
vue.js中created方法作用
2018/03/30 Javascript
JavaScript深拷贝和浅拷贝概念与用法实例分析
2018/06/07 Javascript
基于vue-router 多级路由redirect 重定向的问题
2018/09/03 Javascript
JS实现字体背景跑马灯
2020/01/06 Javascript
JS前后端实现身份证号验证代码解析
2020/07/23 Javascript
js中延迟加载和预加载的具体使用
2021/01/14 Javascript
django1.8使用表单上传文件的实现方法
2016/11/04 Python
有趣的python小程序分享
2017/12/05 Python
让你Python到很爽的加速递归函数的装饰器
2019/05/26 Python
django框架自定义模板标签(template tag)操作示例
2019/06/24 Python
基于python 取余问题(%)详解
2020/06/03 Python
keras自定义损失函数并且模型加载的写法介绍
2020/06/15 Python
python各种excel写入方式的速度对比
2020/11/10 Python
CSS3常用的几种颜色渐变模式总结
2016/11/18 HTML / CSS
白酒市场开发计划书
2014/01/09 职场文书
煤矿百日安全活动总结
2015/05/07 职场文书
2016三八妇女节慰问信
2015/11/30 职场文书
幼儿园教师辞职信
2019/06/21 职场文书
导游词之晋城蟒河
2019/12/12 职场文书
Python一些基本的图像操作和处理总结
2021/06/23 Python