PageRenderTime 26ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/common/components/BaseCrudController.php

https://gitlab.com/joepa37/ierschool
PHP | 402 lines | 237 code | 56 blank | 109 comment | 21 complexity | 78bbf2a31b0a1f9300f3a164a56f9fa3 MD5 | raw file
  1. <?php
  2. namespace common\components;
  3. use yii\data\ActiveDataProvider;
  4. use yii\db\ActiveRecord;
  5. use yii\filters\VerbFilter;
  6. use yii\helpers\ArrayHelper;
  7. use yii\web\Cookie;
  8. use yii\web\NotFoundHttpException;
  9. use yii\web\Response;
  10. use Yii;
  11. class BaseCrudController extends BaseController
  12. {
  13. use \common\components\log\BaseTraitController;
  14. /**
  15. * @var ActiveRecord
  16. */
  17. public $modelClass;
  18. /**
  19. * @var ActiveRecord
  20. */
  21. public $modelSearchClass;
  22. /**
  23. * @var string
  24. */
  25. public $scenarioOnCreate;
  26. /**
  27. * @var string
  28. */
  29. public $scenarioOnUpdate;
  30. /**
  31. * Actions that will be disabled
  32. *
  33. * List of available actions:
  34. *
  35. * ['index', 'view', 'create', 'update', 'delete', 'toggle-attribute',
  36. * 'bulk-activate', 'bulk-deactivate', 'bulk-delete', 'grid-sort', 'grid-page-size']
  37. *
  38. * @var array
  39. */
  40. public $disabledActions = [];
  41. //public $directory;
  42. /**
  43. * Opposite to $disabledActions. Every action from AdminDefaultController except those will be disabled
  44. *
  45. * But if action listed both in $disabledActions and $enableOnlyActions
  46. * then it will be disabled
  47. *
  48. * @var array
  49. */
  50. public $enableOnlyActions = [];
  51. /**
  52. * List of actions in this controller. Needed fo $enableOnlyActions
  53. *
  54. * @var array
  55. */
  56. protected $_implementedActions = ['index', 'view', 'create', 'update', 'delete', 'toggle-attribute',
  57. 'bulk-activate', 'bulk-deactivate', 'bulk-delete', 'grid-sort', 'grid-page-size'];
  58. public function behaviors()
  59. {
  60. return ArrayHelper::merge(parent::behaviors(),[
  61. 'verbs' => [
  62. 'class' => VerbFilter::className(),
  63. 'actions' => [
  64. 'delete' => ['post'],
  65. ],
  66. ],
  67. ]);
  68. }
  69. /**
  70. * Lists all models.
  71. *
  72. * @return mixed
  73. */
  74. public function actionIndex()
  75. {
  76. $searchModel = $this->modelSearchClass ? new $this->modelSearchClass : null;
  77. if ( $searchModel )
  78. {
  79. $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());
  80. }
  81. else
  82. {
  83. $modelClass = $this->modelClass;
  84. $dataProvider = new ActiveDataProvider([
  85. 'query' => $modelClass::find(),
  86. 'pagination' => [
  87. 'pageSize' => Yii::$app->request->cookies->getValue('_grid_page_size', 20),
  88. ],
  89. ]);
  90. }
  91. return $this->renderIsAjax($this->directory.'index', compact('dataProvider', 'searchModel'));
  92. }
  93. /**
  94. * Displays a single model.
  95. *
  96. * @param integer $id
  97. *
  98. * @return mixed
  99. */
  100. public function actionView($id)
  101. {
  102. $this->logParam1 = $id;
  103. return $this->renderIsAjax($this->directory.'view', [
  104. 'model' => $this->findModel($id),
  105. ]);
  106. }
  107. /**
  108. * Creates a new model.
  109. * If creation is successful, the browser will be redirected to the 'view' page.
  110. *
  111. * @return mixed
  112. */
  113. public function actionCreate()
  114. {
  115. $model = new $this->modelClass;
  116. if ( $this->scenarioOnCreate )
  117. {
  118. $model->scenario = $this->scenarioOnCreate;
  119. }
  120. if ( $model->load(Yii::$app->request->post()) && $model->save() )
  121. {
  122. if(Yii::$app->request->isAjax)
  123. {
  124. Yii::$app->response->format = Response::FORMAT_JSON;
  125. return [
  126. 'status' => 200,
  127. 'message' => 'Registro creado exitosamente.',
  128. ];
  129. }
  130. $redirect = $this->getRedirectPage('create', $model);
  131. return $redirect === false ? '' : $this->redirect($redirect);
  132. }
  133. return $this->renderIsAjax($this->directory.'create', compact('model'));
  134. }
  135. /**
  136. * Updates an existing model.
  137. * If update is successful, the browser will be redirected to the 'view' page.
  138. *
  139. * @param integer $id
  140. *
  141. * @return mixed
  142. */
  143. public function actionUpdate($id)
  144. {
  145. $this->logParam1 = $id;
  146. $model = $this->findModel($id);
  147. if ( $this->scenarioOnUpdate )
  148. {
  149. $model->scenario = $this->scenarioOnUpdate;
  150. }
  151. if ( $model->load(Yii::$app->request->post()) AND $model->save())
  152. {
  153. if(Yii::$app->request->isAjax)
  154. {
  155. Yii::$app->response->format = Response::FORMAT_JSON;
  156. return [
  157. 'status' => 200,
  158. 'message' => 'Registro actualizado exitosamente.',
  159. ];
  160. }
  161. $redirect = $this->getRedirectPage('update', $model);
  162. return $redirect === false ? '' : $this->redirect($redirect);
  163. }
  164. return $this->renderIsAjax($this->directory.'update', compact('model'));
  165. }
  166. /**
  167. * Deletes an existing model.
  168. * If deletion is successful, the browser will be redirected to the 'index' page.
  169. *
  170. * @param integer $id
  171. *
  172. * @return mixed
  173. */
  174. public function actionDelete($id)
  175. {
  176. $this->logParam1 = $id;
  177. $model = $this->findModel($id);
  178. $model->delete();
  179. if(Yii::$app->request->isAjax)
  180. {
  181. Yii::$app->response->format = Response::FORMAT_JSON;
  182. return [
  183. 'status' => 200,
  184. 'message' => 'Registro eliminado exitosamente.',
  185. ];
  186. }
  187. $redirect = $this->getRedirectPage('delete', $model);
  188. return $redirect === false ? '' : $this->redirect($redirect);
  189. }
  190. /**
  191. * @inheritdoc
  192. */
  193. public function beforeAction($action)
  194. {
  195. if ( parent::beforeAction($action) )
  196. {
  197. if ( $this->enableOnlyActions !== [] AND in_array($action->id, $this->_implementedActions) AND !in_array($action->id, $this->enableOnlyActions) )
  198. {
  199. throw new NotFoundHttpException('Page not found');
  200. }
  201. if ( in_array($action->id, $this->disabledActions) )
  202. {
  203. throw new NotFoundHttpException('Page not found');
  204. }
  205. return true;
  206. }
  207. return false;
  208. }
  209. /**
  210. * Finds the model based on its primary key value.
  211. * If the model is not found, a 404 HTTP exception will be thrown.
  212. *
  213. * @param mixed $id
  214. *
  215. * @return ActiveRecord the loaded model
  216. * @throws NotFoundHttpException if the model cannot be found
  217. */
  218. protected function findModel($id)
  219. {
  220. $modelClass = $this->modelClass;
  221. if ( ($model = $modelClass::findOne($id)) !== null )
  222. {
  223. return $model;
  224. }
  225. else
  226. {
  227. throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
  228. }
  229. }
  230. /**
  231. * Define redirect page after update, create, delete, etc
  232. *
  233. * @param string $action
  234. * @param ActiveRecord $model
  235. *
  236. * @return string|array
  237. */
  238. protected function getRedirectPage($action, $model = null)
  239. {
  240. switch ($action)
  241. {
  242. case 'delete':
  243. return Yii::$app->request->isAjax ? false : ['index'];
  244. break;
  245. case 'update':
  246. return Yii::$app->request->isAjax ? false : ['view', 'id'=>$model->id];
  247. break;
  248. case 'create':
  249. return Yii::$app->request->isAjax ? false : ['view', 'id'=>$model->id];
  250. break;
  251. default:
  252. return ['index'];
  253. }
  254. }
  255. /**
  256. * Set page size for grid
  257. */
  258. public function actionGridPageSize()
  259. {
  260. if ( Yii::$app->request->post('grid-page-size') )
  261. {
  262. $cookie = new Cookie([
  263. 'name' => '_grid_page_size',
  264. 'value' => Yii::$app->request->post('grid-page-size'),
  265. 'expire' => time() + 86400 * 365, // 1 year
  266. ]);
  267. Yii::$app->response->cookies->add($cookie);
  268. }
  269. }
  270. /**
  271. * Sorting items in grid
  272. */
  273. public function actionGridSort()
  274. {
  275. if ( Yii::$app->request->post('sorter') )
  276. {
  277. $sortArray = Yii::$app->request->post('sorter',[]);
  278. $modelClass = $this->modelClass;
  279. $models = $modelClass::findAll(array_keys($sortArray));
  280. foreach ($models as $model)
  281. {
  282. $model->sorter = $sortArray[$model->id];
  283. $model->save(false);
  284. }
  285. }
  286. }
  287. /**
  288. * @param string $attribute
  289. * @param int $id
  290. */
  291. public function actionToggleAttribute($attribute, $id)
  292. {
  293. $model = $this->findModel($id);
  294. $model->{$attribute} = ($model->{$attribute} == 1) ? 0 : 1;
  295. $model->save(false);
  296. }
  297. /**
  298. * Activate all selected grid items
  299. */
  300. public function actionBulkActivate($attribute = 'active')
  301. {
  302. $this->logParam1 = implode(';', Yii::$app->request->post('selection', []));
  303. $this->logParam2 = $attribute;
  304. if ( Yii::$app->request->post('selection') )
  305. {
  306. $modelClass = $this->modelClass;
  307. $modelClass::updateAll(
  308. [$attribute=>1],
  309. ['id'=>Yii::$app->request->post('selection', [])]
  310. );
  311. }
  312. }
  313. /**
  314. * Deactivate all selected grid items
  315. */
  316. public function actionBulkDeactivate($attribute = 'active')
  317. {
  318. $this->logParam1 = implode(';', Yii::$app->request->post('selection', []));
  319. $this->logParam2 = $attribute;
  320. if ( Yii::$app->request->post('selection') )
  321. {
  322. $modelClass = $this->modelClass;
  323. $modelClass::updateAll(
  324. [$attribute=>0],
  325. ['id'=>Yii::$app->request->post('selection', [])]
  326. );
  327. }
  328. }
  329. /**
  330. * Deactivate all selected grid items
  331. */
  332. public function actionBulkDelete()
  333. {
  334. $this->logParam1 = implode(';', Yii::$app->request->post('selection', []));
  335. if ( Yii::$app->request->post('selection') )
  336. {
  337. $modelClass = $this->modelClass;
  338. foreach (Yii::$app->request->post('selection', []) as $id)
  339. {
  340. $model = $modelClass::findOne($id);
  341. if ( $model )
  342. $model->delete();
  343. }
  344. }
  345. }
  346. }