ProvincesController.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. <?php
  2. namespace backend\modules\common\controllers;
  3. use Yii;
  4. use yii\web\Response;
  5. use common\helpers\ResultHelper;
  6. use common\models\common\Provinces;
  7. use common\traits\Curd;
  8. use backend\controllers\BaseController;
  9. /**
  10. * Class ProvincesController
  11. * @package backend\modules\common\controllers
  12. */
  13. class ProvincesController extends BaseController
  14. {
  15. use Curd;
  16. /**
  17. * @var Provinces
  18. */
  19. public $modelClass = Provinces::class;
  20. /**
  21. * Lists all Tree models.
  22. * @return mixed
  23. */
  24. public function actionIndex()
  25. {
  26. return $this->render('index', []);
  27. }
  28. /**
  29. * @param $pid
  30. * @return array
  31. */
  32. public function actionList($pid)
  33. {
  34. Yii::$app->response->format = Response::FORMAT_JSON;
  35. $data = Yii::$app->services->provinces->getCityByPid($pid);
  36. $jsTreeData = [];
  37. foreach ($data as $datum) {
  38. $data = [
  39. 'id' => $datum['id'],
  40. 'parent' => !empty($datum['pid']) ? $datum['pid'] : '#',
  41. 'text' => trim($datum['title']),
  42. 'icon' => 'fa fa-folder',
  43. 'children' => true
  44. ];
  45. $jsTreeData[] = $data;
  46. }
  47. return $jsTreeData;
  48. }
  49. /**
  50. * 编辑/创建
  51. *
  52. * @return mixed
  53. */
  54. public function actionEdit()
  55. {
  56. $id = Yii::$app->request->get('id', null);
  57. $model = $this->findModel($id);
  58. $model->pid = Yii::$app->request->get('pid', null) ?? $model->pid; // 父id
  59. if ($model->load(Yii::$app->request->post())) {
  60. if (!$model->save()) {
  61. return ResultHelper::json(422, $this->getError($model));
  62. }
  63. return ResultHelper::json(200, '修改成功', $model);
  64. }
  65. $map = ['0' => '顶级'];
  66. if ($model->pid && $parent = Yii::$app->services->provinces->findById($model->pid)) {
  67. $map = [$parent['id'] => $parent['title']];
  68. }
  69. return $this->renderAjax($this->action->id, [
  70. 'model' => $model,
  71. 'map' => $map,
  72. ]);
  73. }
  74. /**
  75. * 移动
  76. *
  77. * @param $id
  78. * @param int $pid
  79. */
  80. public function actionMove($id, $pid = 0)
  81. {
  82. $model = $this->findModel($id);
  83. $model->pid = $pid;
  84. $model->save();
  85. }
  86. /**
  87. * 删除
  88. *
  89. * @param $id
  90. * @return mixed
  91. * @throws \Throwable
  92. * @throws \yii\db\StaleObjectException
  93. */
  94. public function actionDelete($id)
  95. {
  96. if ($this->findModel($id)->delete()) {
  97. return ResultHelper::json(200, '删除成功');
  98. }
  99. return ResultHelper::json(422, '删除失败');
  100. }
  101. }
粤ICP备19079148号