准确说,初学框架那段时间,使用下拉列表可不是件容易的事,包括怎么引入类class都需要去百度,手册找,而且几乎很多次都是徒劳无功.第一次使用地区三级联动还是用的网上的js插件,才插件中别人已经把地区信息以数组或者json的格式包装好了,不需要提供额外的数据
库支持,好处是直接使用.坏处是地区信息都很旧,比如我家所在地,记得是2012年已经将毕节地区改为市了,但是插件中还是使用毕业地区,这虽然没什么错,但已经说明这些数据其实也是作者搜索出来的,别的地方没有考证过,但肯定也有一些地区信息,已经在最近的几年被更改
过了,因此使用一定意义上是不正确的.
几乎在我遇到的项目中,地区信息都有自己的数据库,而且后台都有地区信息添加修改功能,所以地区的插件其实是不需要的,基本都要自己去写,这次也不例外.
下面我就把一个完整的使用过程罗列:
- 首先当然是数据库信息,这里就不列出,一般是三张基本表省,市,区县,以及小区等
- 模型通常直接使用gii生成即可
- 通过模型获取各级数据,需要一个中间文件,也可以直接写在模型中,只是会比较乱
1. 基础
BaseLib.php
namespace common\louli\service;
use common\models\base\Area;
use common\models\base\City;
use common\models\base\Community;
class BaseLib
{
/**
* 市列表
*
* @param $condition
* @param array $params
* @param bool $isArray
* @return array|\yii\db\ActiveRecord[]
*/
public function getCity($condition, $params = [], $isArray = false)
{
$query = City::find()->where($condition, $params);
if ($isArray) {
$query->asArray();
}
$result = $query->all();
return $result;
}
/**
* 区列表
*
* @param $condition
* @param array $params
* @param bool $isArray
* @return array|\yii\db\ActiveRecord[]
*/
public function getArea($condition, $params = [], $isArray = false)
{
$query = Area::find()->where($condition, $params);
if ($isArray) {
$query->asArray();
}
$result = $query->all();
return $result;
}
/**
* 区详细信息
*
* @param $id
* @return null|static
*/
public function getAreaDetail($id)
{
$query = Area::findOne($id);
return $query;
}
/**
* 小区列表
*
* @param $condition
* @param array $params
* @param bool $isArray
* @return array|\yii\db\ActiveRecord[]
*/
public function getCommunity($condition, $params = [], $isArray = true)
{
$query = Community::find()->where($condition, $params);
if ($isArray) {
$query->asArray();
}
$result = $query->all();
return $result;
}
/**
* 小区详细信息
*
* @param $id
* @return null|static
*/
public function getCommunityDetail($id)
{
$query = Community::findOne($id);
return $query;
}
}
2. 控制器
HuangYeErrorController.php
/**
* 黄页纠错
*
* @return string
*/
public function actionIndex()
{
$searchModel = new HuangYeErrorSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//市-区-小区
$params = isset($_GET['HuangYeErrorSearch']) ? $_GET['HuangYeErrorSearch'] : [];
$cities = BaseController::getCity();
$cityId = isset($params['cityName']) && $params['cityName'] ? intval($params['cityName']) : $cities[0]->id;
$searchModel->cityName = isset($params['cityName']) ? intval($params['cityName']) : 0;
$areas = BaseController::getArea($cityId);
$areaId = isset($params['areaName']) && $params['areaName'] ? intval($params['areaName']) : $areas[0]->id;
$searchModel->areaName = isset($params['areaName']) ? intval($params['areaName']) : 0;
$communities = BaseController::getCommunity($areaId, false);
$searchModel->communityName = isset($params['communityName']) ? intval($params['communityName']) : 0;
//获得类别
$parentId['id'] = 0;
$order = '';
$categories = BaseController::getCategories($parentId, $order, false, true);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'cities' => $cities,
'areas' => $areas,
'communities' => $communities,
'categories' => $categories
]);
}
这里我加了一个中间文件baseController.php,以后在模板中调用就只需要这个固定的路径,毕竟需要用到的模板不止一个,每个控制器中都写的话需要修改的时候就必须每一处都要修改
namespace admin\modules\service\controllers;
use common\louli\service\BaseLib;
use common\louli\service\CategoryLib;
use yii\web\Controller;
/**
* 地区信息和类别
*
* Class BaseController
* @package admin\modules\service\controllers
*/
class BaseController extends Controller
{
/**
* 市,默认北京市,省id是1
*
* @return array|\yii\db\ActiveRecord[]
*/
public static function getCity()
{
$condition = ' `status` = :status';
$params[':status'] = 1;
$bLib = new BaseLib();
$result = $bLib->getCity($condition, $params);
return $result;
}
/**
* 区
*
* @param $cityId
* @return array|\yii\db\ActiveRecord[]
*/
public static function getArea($cityId)
{
$condition = ' `cityid` = :cityid AND `status` = :status';
$params[':cityid'] = $cityId;
$params[':status'] = 1;
$bLib = new BaseLib();
$result = $bLib->getArea($condition, $params);
return $result;
}
/**
* 小区
*
* @param $areaId
* @param bool $flag
* @return array|\yii\db\ActiveRecord[]
*/
public static function getCommunity($areaId, $flag = true)
{
$condition = ' `areaid` = :areaid AND `status` = :status';
$params[':areaid'] = $areaId;
$params[':status'] = 1;
$bLib = new BaseLib();
$result = $bLib->getCommunity($condition, $params, $flag);
return $result;
}
/**
* ajax请求区
*
* @param $id
* @return string
*/
public function actionGetAreaList($id)
{
$option = '';
$result = self::getArea($id);
if ($result) {
foreach ($result as $value) {
$option .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
}
} else {
$option .= '<option value="0">暂未开通可选择的区</option>';
}
echo $option;
}
/**
* 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;
}
/**
* 搜索小区
*
* @param $id
* @param $word
* @return string
*/
public function actionSearchCommunity($id, $word)
{
$condition = ' `areaid` = :areaid AND `status` = :status AND `name` LIKE :name';
$params[':areaid'] = $id;
$params[':status'] = 1;
$params[':name'] = '%' . $word . '%';
$countLib = new BaseLib();
$result = $countLib->getCommunity($condition, $params);
$option = '';
if (! empty($result)) {
$option .= '<option value="0">请选择小区</option>';
foreach ($result as $value) {
$option .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
}
} else {
$option .= '<option value="0">没有查找到小区</option>';
}
echo $option;
}
}
3. 视图
<div class="row">
<?= $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">
<label for="keyword" class="sr-only">请输入小区名</label>
<input class="form-control" id="keyword" placeholder="请输入小区名" value="" />
</div>
<div class="col-lg-1">
<label for="search-community" class="sr-only">搜索</label>
<button type="button" id="search-community" class="btn btn-info">搜索</button>
</div>
</div>
<script>
//市地址改变
$("#huangyeerrorsearch-cityname").change(function() {
//市id值
var cityid = $(this).val();
$("#huangyeerrorsearch-areaname").html("<option value=\"0\">请选择区县</option>");
$("#huangyeerrorsearch-communityname").html("<option value=\"0\">请选择小区</option>");
if (cityid > 0) {
getArea(cityid);
}
});
//区地址改变
$("#huangyeerrorsearch-areaname").change(function() {
//区id值
var areaid = $(this).val();
$("#huangyeerrorsearch-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) {
$("#huangyeerrorsearch-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) {
$("#huangyeerrorsearch-communityname").append(d);
}
});
}
//搜索小区
$("#search-community").click(function() {
var word = $("#keyword").val();
var areaid = $("#huangyeerrorsearch-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) {
$("#huangyeerrorsearch-communityname").html(d);
}
});
}
});
</script>