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 URL编码解码函数代码
Mar 10 PHP
php 操作excel文件的方法小结
Dec 31 PHP
apache配置虚拟主机的方法详解
Jun 17 PHP
php模拟ping命令(php exec函数的使用方法)
Oct 25 PHP
单台服务器的PHP进程之间实现共享内存的方法
Jun 13 PHP
ThinkPHP3.1.3版本新特性概述
Jun 19 PHP
ThinkPHP之foreach标签使用概述
Jun 30 PHP
PHP实现大数(浮点数)取余的方法
Feb 18 PHP
[原创]PHP正则匹配中英文、数字及下划线的方法【用户名验证】
Aug 01 PHP
yii2中LinkPager增加总页数和总记录数的实例
Aug 28 PHP
php+laravel依赖注入知识点总结
Nov 04 PHP
php ActiveMQ的安装与使用方法图文教程
Feb 23 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 MVC模式在网站架构中的实现分析
2010/03/04 PHP
php 转换字符串编码 iconv与mb_convert_encoding的区别说明
2011/11/10 PHP
Symfony2安装第三方Bundles实例详解
2016/02/04 PHP
thinkPHP框架动态配置用法实例分析
2018/06/14 PHP
PHP 扩展Memcached命令用法实例总结
2020/06/04 PHP
jQuery在html有效在jsp无效的原因及解决方法
2013/08/02 Javascript
JQuery页面图片切换和新闻列表滚动效果的具体实现
2013/09/26 Javascript
Javascript学习笔记之数组的遍历和 length 属性
2014/11/23 Javascript
基于jQuery实现下拉框
2014/11/24 Javascript
javascript操作字符串的原生方法
2014/12/22 Javascript
js的window.showModalDialog及window.open用法实例分析
2015/01/29 Javascript
jquery插件uploadify实现带进度条的文件批量上传
2015/12/13 Javascript
详解js的延迟对象、跨域、模板引擎、弹出层、AJAX【附实例下载】
2016/12/19 Javascript
jQuery实现动态添加tr到table的方法
2016/12/26 Javascript
js获取指定时间的前几秒
2017/04/05 Javascript
浅谈angularjs中响应回车事件
2017/04/24 Javascript
搭建element-ui的Vue前端工程操作实例
2018/02/23 Javascript
使用layui+ajax实现简单的菜单权限管理及排序的方法
2019/09/10 Javascript
微信小程序间使用navigator跳转传值问题实例分析
2020/03/27 Javascript
Node.js利用Express实现用户注册登陆功能(推荐)
2020/10/26 Javascript
[01:06:07]2014 DOTA2国际邀请赛中国区预选赛5.21 DT VS CIS
2014/05/22 DOTA
TensorFlow的环境配置与安装教程详解(win10+GeForce GTX1060+CUDA 9.0+cuDNN7.3+tensorflow-gpu 1.12.0+python3.5.5)
2020/06/22 Python
英国领先的高街书籍专家:Waterstones
2018/02/01 全球购物
加拿大国民体育购物网站:National Sports
2018/11/04 全球购物
泰海淘:泰国king Power王权免税集团旗下跨境海淘综合型电商
2020/07/26 全球购物
瑞典在互联网上最大的宠物商店:Animail
2020/10/31 全球购物
党章学习思想汇报
2014/01/14 职场文书
运动会宣传口号
2014/06/09 职场文书
音乐学专业求职信
2014/07/22 职场文书
市场营销毕业求职信
2014/08/07 职场文书
关于群众路线的心得体会
2014/11/05 职场文书
业务员年终工作总结2015
2015/05/28 职场文书
2016重阳节红领巾广播稿
2015/12/18 职场文书
2016校本研修培训心得体会
2016/01/08 职场文书
2016年社区党支部公开承诺书
2016/03/25 职场文书
Python编程中内置的NotImplemented类型的用法
2022/03/23 Python