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
Nov 25 PHP
在WAMP环境下搭建ZendDebugger php调试工具的方法
Jul 18 PHP
php操作xml
Oct 27 PHP
php session劫持和防范的方法
Nov 12 PHP
2014年最新推荐的10款 PHP 开发框架
Aug 01 PHP
php递归遍历删除文件的方法
Apr 17 PHP
Zend Framework动作助手Redirector用法实例详解
Mar 05 PHP
php单链表实现代码分享
Jul 04 PHP
浅谈PHP的排列组合(如输入a,b,c 输出他们的全部组合)
Mar 14 PHP
PHP mysqli事务操作常用方法分析
Jul 22 PHP
PHP中使用CURL发送get/post请求上传图片批处理功能
Oct 15 PHP
PHP DB 数据库连接类定义与用法示例
Mar 11 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
echo, print, printf 和 sprintf 区别
2006/12/06 PHP
php学习笔记 面向对象的构造与析构方法
2011/06/13 PHP
php 解析xml 的四种方法详细介绍
2016/10/26 PHP
PHP date()格式MySQL中插入datetime方法
2019/01/29 PHP
php源码的安装方法和实例
2019/09/26 PHP
php中文语义分析实现方法示例
2019/09/28 PHP
一个可以兼容IE FF的加为首页与加入收藏实现代码
2009/11/02 Javascript
javascript开发技术大全-第3章 js数据类型
2011/07/03 Javascript
js常用代码段收集
2011/10/28 Javascript
JavaScript字符串对象的concat方法实例(用于连接两个或多个字符串)
2014/10/16 Javascript
JavaScript中判断变量是数组、函数或是对象类型的方法
2015/02/25 Javascript
javascript与css3动画结合使用小结
2015/03/11 Javascript
javascript拖拽应用实例
2016/03/25 Javascript
JS采用绝对定位实现回到顶部效果完整实例
2016/06/20 Javascript
dropload.js插件下拉刷新和上拉加载使用详解
2017/10/20 Javascript
jQuery实现弹窗下底部页面禁止滑动效果
2017/12/19 jQuery
vue中阻止click事件冒泡,防止触发另一个事件的方法
2018/02/08 Javascript
Elementui表格组件+sortablejs实现行拖拽排序的示例代码
2019/08/28 Javascript
[36:14]DOTA2上海特级锦标赛D组小组赛#1 EG VS COL第二局
2016/02/28 DOTA
Python减少循环层次和缩进的技巧分析
2016/03/15 Python
Python连接phoenix的方法示例
2017/09/29 Python
Python基础语言学习笔记总结(精华)
2017/11/14 Python
python OpenCV学习笔记实现二维直方图
2018/02/08 Python
浅谈python爬虫使用Selenium模拟浏览器行为
2018/02/23 Python
Python一句代码实现找出所有水仙花数的方法
2018/11/13 Python
python实现爬山算法的思路详解
2019/04/09 Python
你应该知道的30个css选择器
2014/03/19 HTML / CSS
英国天然保健品网站:Simply Supplements
2017/03/22 全球购物
小学毕业感言500字
2014/02/28 职场文书
农村面貌改造提升实施方案
2014/03/18 职场文书
四查四看整改措施
2014/09/19 职场文书
政工师工作总结2015
2015/05/26 职场文书
电台广播稿范文
2015/08/19 职场文书
如何使用JavaScript策略模式校验表单
2021/04/29 Javascript
你需要掌握的20个Python常用技巧
2022/02/28 Python
HTML5中的DOCUMENT.VISIBILITYSTATE属性详解
2023/05/07 HTML / CSS