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 相关文章推荐
Get或Post提交值的非法数据处理
Oct 09 PHP
解密ThinkPHP3.1.2版本之模块和操作映射
Jun 19 PHP
从零开始学YII2框架(三)扩展插件yii2-gird
Aug 20 PHP
ThinkPHP中处理表单中的注意事项
Nov 22 PHP
学习php设计模式 php实现模板方法模式
Dec 08 PHP
php模板引擎技术简单实现
Mar 15 PHP
PHP实现双链表删除与插入节点的方法示例
Nov 11 PHP
PHP+jQuery实现即点即改功能示例
Feb 21 PHP
浅谈php://filter的妙用
Mar 05 PHP
PHP高并发和大流量解决方案整理
Dec 24 PHP
laravel5.6 框架邮件队列database驱动简单demo示例
Jan 26 PHP
PHP8.0新功能之Match表达式的使用
Jul 19 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下10件你也许并不了解的事情
2008/09/11 PHP
php过滤XSS攻击的函数
2013/11/12 PHP
ThinkPHP实现带验证码的文件上传功能实例
2014/11/01 PHP
PHP闭包函数详解
2016/02/13 PHP
PHP+jQuery实现双击修改table表格功能示例
2019/02/21 PHP
PHP使用PDO操作sqlite数据库应用案例
2019/03/07 PHP
JQuery 确定css方框模型(盒模型Box Model)
2010/01/22 Javascript
extjs 的权限问题 要求控制的对象是 菜单,按钮,URL
2010/03/09 Javascript
让html页面不缓存js的实现方法
2014/10/31 Javascript
js实现跨域的4种实用方法原理分析
2015/10/29 Javascript
详解Angularjs filter过滤器
2016/02/06 Javascript
遍历js中对象的属性和值的实例
2016/11/21 Javascript
javascript实现鼠标点击页面 移动DIV
2016/12/02 Javascript
React创建组件的三种方式及其区别
2017/01/12 Javascript
Vue实现路由跳转和嵌套
2017/06/20 Javascript
jQuery实现的手动拖动控制进度条效果示例【测试可用】
2018/04/18 jQuery
vue中的ref和$refs的使用
2018/11/22 Javascript
重学 JS:为啥 await 不能用在 forEach 中详解
2019/04/15 Javascript
详解为什么Vue中不要用index作为key(diff算法)
2020/04/04 Javascript
[00:12]DAC2018 Miracle-站上中单舞台,他能否再写奇迹?
2018/04/06 DOTA
Python开发编码规范
2006/09/08 Python
Python 调用DLL操作抄表机
2009/01/12 Python
Mac中升级Python2.7到Python3.5步骤详解
2017/04/27 Python
python中numpy包使用教程之数组和相关操作详解
2017/07/30 Python
Python加载带有注释的Json文件实例
2018/05/23 Python
一篇文章搞定Python操作文件与目录
2019/08/13 Python
python实现多线程端口扫描
2019/08/31 Python
pygame实现俄罗斯方块游戏(基础篇2)
2019/10/29 Python
Python基于read(size)方法读取超大文件
2020/03/12 Python
Python如何绘制日历图和热力图
2020/08/07 Python
Python3合并两个有序数组代码实例
2020/08/11 Python
python可视化分析的实现(matplotlib、seaborn、ggplot2)
2021/02/03 Python
Canvas制作旋转的太极的示例
2018/03/09 HTML / CSS
国外的一些J2EE面试题一
2012/10/13 面试题
护理职业应聘自荐书
2013/09/29 职场文书
Python中glob库实现文件名的匹配
2021/06/18 Python