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入门速成教程
Mar 19 PHP
php运行出现Call to undefined function curl_init()的解决方法
Nov 02 PHP
php中配置文件操作 如config.php文件的读取修改等操作
Jul 07 PHP
PHP判断图片格式的七种方法小结
Jun 03 PHP
php 获取页面中指定内容的实现类
Jan 23 PHP
php的zip解压缩类pclzip使用示例
Mar 14 PHP
dedecms中使用php语句指南
Nov 13 PHP
非常实用的php验证码类
May 15 PHP
浅析PHP中的i++与++i的区别及效率
Jun 15 PHP
PHP获取IP地址所在地信息的实例(使用纯真IP数据库qqwry.dat)
Nov 15 PHP
redirect_uri参数错误的解决方法(必看)
Feb 16 PHP
PHP redis实现超迷你全文检索
Mar 04 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长字符串定义方法
2012/07/12 PHP
php类的自动加载操作实例详解
2016/09/28 PHP
JavaScript/jQuery 表单美化插件小结
2012/02/14 Javascript
JS实现日期时间动态显示的方法
2015/12/07 Javascript
详解Javascript继承的实现
2016/03/25 Javascript
jQuery查找节点并获取节点属性的方法
2016/09/09 Javascript
JavaScript 计算笛卡尔积实例详解
2016/12/02 Javascript
Node.JS中快速扫描端口并发现局域网内的Web服务器地址(80)
2017/09/18 Javascript
JS点击动态添加标签、删除指定标签的代码
2018/04/18 Javascript
Element UI 自定义正则表达式验证方法
2018/09/04 Javascript
Angular 实现输入框中显示文章标签的实例代码
2018/11/07 Javascript
原生js实现Flappy Bird小游戏
2018/12/24 Javascript
JQuery属性操作与循环用法示例
2019/05/15 jQuery
vue实现自定义H5视频播放器的方法步骤
2019/07/01 Javascript
详解Vue 项目中的几个实用组件(ts)
2019/10/29 Javascript
js实现手表表盘时钟与圆周运动
2020/09/18 Javascript
[03:06]2018年度CS GO最具人气解说-完美盛典
2018/12/16 DOTA
对python list 遍历删除的正确方法详解
2018/06/29 Python
使用Fabric自动化部署Django项目的实现
2019/09/27 Python
python GUI库图形界面开发之PyQt5信号与槽基本操作
2020/02/25 Python
Python应用自动化部署工具Fabric原理及使用解析
2020/11/30 Python
移动端解决悬浮层(悬浮header、footer)会遮挡住内容的3种方法
2015/03/27 HTML / CSS
JOSEPH官网:英国奢侈时尚品牌
2018/01/31 全球购物
工程测量与监理专业应届生求职信
2013/11/27 职场文书
18岁生日感言
2014/01/12 职场文书
烹调加工管理制度
2014/02/04 职场文书
学生评语大全
2014/04/18 职场文书
工厂门卫的岗位职责
2014/07/27 职场文书
2014年接待工作总结
2014/11/26 职场文书
先进员工事迹材料
2014/12/20 职场文书
公司租车协议书
2015/01/29 职场文书
庆祝教师节主持词
2015/07/06 职场文书
考教师资格证不要错过的4个最佳时机
2019/07/17 职场文书
实习报告范文之电话客服岗位
2019/07/26 职场文书
Pillow图像处理库安装及使用
2022/04/12 Python
安装harbor作为docker镜像仓库的问题
2022/06/14 Servers