Yii2實現中國省市區三級聯動執行個體

來源:互聯網
上載者:User
Yii2實現中國省市區三級聯動執行個體

安裝

添加到你的composer.json檔案

"chenkby/yii2-region": "dev-master"

切換到項目目錄

composer update;

3、配置

1) 在地區的Model中添加以下方法

public static function getRegion($parentId=0){  $result = static::find()->where(['parent_id'=>$parentId])->asArray()->all();  return ArrayHelper::map($result, 'id', 'name');}

2) 在controller中添加以下action

public function actions(){  $actions=parent::actions();  $actions['get-region']=[    'class'=>\chenkby\region\RegionAction::className(),    'model'=>\app\models\Region::className()  ];  return $actions;}

3) 在common/config裡的main.php中添加 urlManager的enablePrettyUrl的,即隱藏index.php

"urlManager" => [   //用於表明urlManager是否啟用URL美化功能,在Yii1.1中稱為path格式URL,   // Yii2.0中改稱美化。   // 預設不啟用。但實際使用中,特別是產品環境,一般都會啟用。   "enablePrettyUrl" => true,   // 是否啟用嚴格解析,如啟用嚴格解析,要求當前請求應至少匹配1個路由規則,   // 否則認為是無效路由。   // 這個選項僅在 enablePrettyUrl 啟用後才有效。   "enableStrictParsing" => false,   // 是否在URL中顯示入口指令碼。是對美化功能的進一步補充。   "showScriptName" => false,   // 指定續接在URL後面的一個尾碼,如 .html 之類的。僅在 enablePrettyUrl 啟用時有效。   "suffix" => "",   "rules" => [       "<controller:\w+>/<id:\d+>"=>"<controller>/view",    "<controller:\w+>/<action:\w+>"=>"<controller>/<action>"   ],],

4、使用

<?= $form->field($model, 'district')->widget(\chenkby\region\Region::className(),[  'model'=>$model,  'url'=> \yii\helpers\Url::toRoute(['get-region']),  'province'=>[    'attribute'=>'province',    'items'=>Region::getRegion(),    'options'=>['class'=>'form-control form-control-inline','prompt'=>'選擇省份']  ],  'city'=>[    'attribute'=>'city',    'items'=>Region::getRegion($model['province']),    'options'=>['class'=>'form-control form-control-inline','prompt'=>'選擇城市']  ],  'district'=>[    'attribute'=>'district',    'items'=>Region::getRegion($model['city']),    'options'=>['class'=>'form-control form-control-inline','prompt'=>'選擇縣/區']  ]]);?>

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援topic.alibabacloud.com。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.