Yii2 dropdownlist 三级联动概述
本示例详细解析了在Yii2框架中,如何利用dropdownlist组件配合Ajax技术来实现地区数据的三级联动效果。内容涵盖从视图到控制器的完整实现流程,供开发者参考借鉴。
首先是视图层的代码构建部分。
<?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 */
?>
<?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']) ?>
搜索
<?= Html::submitButton('搜索', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?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后端,需要将数据组合成特定的结构直接输出。在使用$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');
}
}
原先采用了多表关联的方式,需要使用joinWith()进行连接,但后来为了提升查询效率,将所有数据整合到了单表中。因为多表查询速度较慢,所以建议尽可能将数据转化为单表结构来处理:
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 .= '' . $value['name'] . '';
}
} else {
$option .= '暂未开通可选择的小区';
}
echo $option;
}
希望上述关于Yii框架下PHP程序设计的经验分享,能对各位读者有所帮助。