Actions.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. <?php
  2. /**
  3. * Copyright © 2015-2017 Ihor Vansach (ihor@magefan.com). All rights reserved.
  4. * See LICENSE.txt for license details (http://opensource.org/licenses/osl-3.0.php).
  5. *
  6. * Glory to Ukraine! Glory to the heroes!
  7. */
  8. namespace Magefan\Blog\Controller\Adminhtml;
  9. /**
  10. * Abstract admin controller
  11. */
  12. abstract class Actions extends \Magento\Backend\App\Action
  13. {
  14. /**
  15. * Form session key
  16. * @var string
  17. */
  18. protected $_formSessionKey;
  19. /**
  20. * Allowed Key
  21. * @var string
  22. */
  23. protected $_allowedKey;
  24. /**
  25. * Model class name
  26. * @var string
  27. */
  28. protected $_modelClass;
  29. /**
  30. * Active menu key
  31. * @var string
  32. */
  33. protected $_activeMenu;
  34. /**
  35. * Store config section key
  36. * @var string
  37. */
  38. protected $_configSection;
  39. /**
  40. * Request id key
  41. * @var string
  42. */
  43. protected $_idKey = 'id';
  44. /**
  45. * Status field name
  46. * @var string
  47. */
  48. protected $_statusField = 'status';
  49. /**
  50. * Save request params key
  51. * @var string
  52. */
  53. protected $_paramsHolder;
  54. /**
  55. * Model Object
  56. * @var \Magento\Framework\Model\AbstractModel
  57. */
  58. protected $_model;
  59. /**
  60. * Core registry
  61. *
  62. * @var \Magento\Framework\Registry
  63. */
  64. protected $_coreRegistry = null;
  65. /**
  66. * Action execute
  67. * @return \Magento\Framework\Controller\ResultInterface
  68. */
  69. public function execute()
  70. {
  71. $_preparedActions = ['index', 'grid', 'new', 'edit', 'save', 'duplicate', 'delete', 'config', 'massStatus'];
  72. $_action = $this->getRequest()->getActionName();
  73. if (in_array($_action, $_preparedActions)) {
  74. $method = '_'.$_action.'Action';
  75. $this->_beforeAction();
  76. $this->$method();
  77. $this->_afterAction();
  78. }
  79. }
  80. /**
  81. * Index action
  82. * @return void
  83. */
  84. protected function _indexAction()
  85. {
  86. if ($this->getRequest()->getParam('ajax')) {
  87. $this->_forward('grid');
  88. return;
  89. }
  90. $this->_view->loadLayout();
  91. $this->_setActiveMenu($this->_activeMenu);
  92. $title = __('Manage %1', $this->_getModel(false)->getOwnTitle(true));
  93. $this->_view->getPage()->getConfig()->getTitle()->prepend($title);
  94. $this->_addBreadcrumb($title, $title);
  95. $this->_view->renderLayout();
  96. }
  97. /**
  98. * Grid action
  99. * @return void
  100. */
  101. protected function _gridAction()
  102. {
  103. $this->_view->loadLayout(false);
  104. $this->_view->renderLayout();
  105. }
  106. /**
  107. * New action
  108. * @return void
  109. */
  110. protected function _newAction()
  111. {
  112. $this->_forward('edit');
  113. }
  114. /**
  115. * Edit action
  116. * @return void
  117. */
  118. public function _editAction()
  119. {
  120. $model = $this->_getModel();
  121. $this->_getRegistry()->register('current_model', $model);
  122. $this->_view->loadLayout();
  123. $this->_setActiveMenu($this->_activeMenu);
  124. $title = $model->getOwnTitle();
  125. if ($model->getId()) {
  126. $breadcrumbTitle = __('Edit %1', $title);
  127. $breadcrumbLabel = $breadcrumbTitle;
  128. } else {
  129. $breadcrumbTitle = __('New %1', $title);
  130. $breadcrumbLabel = __('Create %1', $title);
  131. }
  132. $this->_view->getPage()->getConfig()->getTitle()->prepend(__($title));
  133. $this->_view->getPage()->getConfig()->getTitle()->prepend(
  134. $model->getId() ? $this->_getModelName($model) : __('New %1', $title)
  135. );
  136. $this->_addBreadcrumb($breadcrumbLabel, $breadcrumbTitle);
  137. // restore data
  138. $values = $this->_getSession()->getData($this->_formSessionKey, true);
  139. if ($this->_paramsHolder) {
  140. $values = isset($values[$this->_paramsHolder]) ? $values[$this->_paramsHolder] : null;
  141. }
  142. if ($values) {
  143. $model->addData($values);
  144. }
  145. $this->_view->renderLayout();
  146. }
  147. /**
  148. * Retrieve model name
  149. * @param boolean $plural
  150. * @return string
  151. */
  152. protected function _getModelName(\Magento\Framework\Model\AbstractModel $model)
  153. {
  154. return $model->getName() ?: $model->getTitle();
  155. }
  156. /**
  157. * Save action
  158. * @return void
  159. */
  160. public function _saveAction()
  161. {
  162. $request = $this->getRequest();
  163. if (!$request->isPost()) {
  164. $this->getResponse()->setRedirect($this->getUrl('*/*'));
  165. }
  166. $model = $this->_getModel();
  167. try {
  168. $params = $this->_paramsHolder ? $request->getParam($this->_paramsHolder) : $request->getParams();
  169. $idFieldName = $model->getResource()->getIdFieldName();
  170. if (isset($params[$idFieldName]) && empty($params[$idFieldName])) {
  171. unset($params[$idFieldName]);
  172. }
  173. $model->addData($params);
  174. $this->_beforeSave($model, $request);
  175. $model->save();
  176. $this->_afterSave($model, $request);
  177. $this->messageManager->addSuccess(__('%1 has been saved.', $model->getOwnTitle()));
  178. $this->_setFormData(false);
  179. } catch (\Magento\Framework\Exception\LocalizedException $e) {
  180. $this->messageManager->addError(nl2br($e->getMessage()));
  181. $this->_setFormData();
  182. } catch (\Exception $e) {
  183. $this->messageManager->addException(
  184. $e,
  185. __('Something went wrong while saving this %1. %2',
  186. strtolower($model->getOwnTitle()),
  187. $e->getMessage()
  188. )
  189. );
  190. $this->_setFormData();
  191. }
  192. $hasError = (bool)$this->messageManager->getMessages()->getCountByType(
  193. \Magento\Framework\Message\MessageInterface::TYPE_ERROR
  194. );
  195. if ($request->getParam('isAjax')) {
  196. $block = $this->_objectManager->create('Magento\Framework\View\Layout')->getMessagesBlock();
  197. $block->setMessages($this->messageManager->getMessages(true));
  198. $this->getResponse()->setBody(json_encode(
  199. [
  200. 'messages' => $block->getGroupedHtml(),
  201. 'error' => $hasError,
  202. 'model' => $model->toArray(),
  203. ]
  204. ));
  205. } else {
  206. if ($hasError || $request->getParam('back')) {
  207. $this->_redirect('*/*/edit', [$this->_idKey => $model->getId()]);
  208. } else {
  209. $this->_redirect('*/*');
  210. }
  211. }
  212. }
  213. /**
  214. * Duplicat action
  215. * @return void
  216. */
  217. protected function _duplicateAction()
  218. {
  219. try {
  220. $originModel = $this->_getModel();
  221. if (!$originModel->getId()) {
  222. throw new \Exception("Item is not longer exist.", 1);
  223. }
  224. $model = $originModel->duplicate();
  225. $this->messageManager->addSuccess(__('%1 has been duplicated.', $model->getOwnTitle()));
  226. $this->_redirect('*/*/edit', [$this->_idKey => $model->getId()]);
  227. } catch (Exception $e) {
  228. $this->messageManager->addException(
  229. $e,
  230. __('Something went wrong while saving this %1. %2',
  231. strtolower($model->getOwnTitle()),
  232. $e->getMessage()
  233. )
  234. );
  235. $this->_redirect('*/*/edit', [$this->_idKey => $originModel->getId()]);
  236. }
  237. }
  238. /**
  239. * Before model Save action
  240. * @return void
  241. */
  242. protected function _beforeSave($model, $request) {}
  243. /**
  244. * After model action
  245. * @return void
  246. */
  247. protected function _afterSave($model, $request) {}
  248. /**
  249. * Before action
  250. * @return void
  251. */
  252. protected function _beforeAction() {}
  253. /**
  254. * After action
  255. * @return void
  256. */
  257. protected function _afterAction() {}
  258. /**
  259. * Delete action
  260. * @return void
  261. */
  262. protected function _deleteAction()
  263. {
  264. $ids = $this->getRequest()->getParam($this->_idKey);
  265. if (!is_array($ids)) {
  266. $ids = [$ids];
  267. }
  268. $error = false;
  269. try {
  270. foreach($ids as $id) {
  271. $this->_objectManager->create($this->_modelClass)->setId($id)->delete();
  272. }
  273. } catch (\Magento\Framework\Exception\LocalizedException $e) {
  274. $error = true;
  275. $this->messageManager->addError($e->getMessage());
  276. } catch (\Exception $e) {
  277. $error = true;
  278. $this->messageManager->addException(
  279. $e,
  280. __("We can't delete %1 right now. %2",
  281. strtolower($this->_getModel(false)->getOwnTitle()),
  282. $e->getMessage()
  283. )
  284. );
  285. }
  286. if (!$error) {
  287. $this->messageManager->addSuccess(
  288. __('%1 have been deleted.', $this->_getModel(false)->getOwnTitle(count($ids) > 1))
  289. );
  290. }
  291. $this->_redirect('*/*');
  292. }
  293. /**
  294. * Change status action
  295. * @return void
  296. */
  297. protected function _massStatusAction()
  298. {
  299. $ids = $this->getRequest()->getParam($this->_idKey);
  300. if (!is_array($ids)) {
  301. $ids = [$ids];
  302. }
  303. $model = $this->_getModel(false);
  304. $error = false;
  305. try {
  306. $status = $this->getRequest()->getParam('status');
  307. $statusFieldName = $this->_statusField;
  308. if (is_null($status)) {
  309. throw new \Exception(__('Parameter "Status" missing in request data.'));
  310. }
  311. if (is_null($statusFieldName)) {
  312. throw new \Exception(__('Status Field Name is not specified.'));
  313. }
  314. foreach($ids as $id) {
  315. $this->_objectManager->create($this->_modelClass)
  316. ->load($id)
  317. ->setData($this->_statusField, $status)
  318. ->save();
  319. }
  320. } catch (\Magento\Framework\Exception\LocalizedException $e) {
  321. $error = true;
  322. $this->messageManager->addError($e->getMessage());
  323. } catch (\Exception $e) {
  324. $error = true;
  325. $this->messageManager->addException(
  326. $e,
  327. __("We can't change status of %1 right now. %2",
  328. strtolower($model->getOwnTitle()),
  329. $e->getMessage()
  330. )
  331. );
  332. }
  333. if (!$error) {
  334. $this->messageManager->addSuccess(
  335. __('%1 status have been changed.', $model->getOwnTitle(count($ids) > 1))
  336. );
  337. }
  338. $this->_redirect('*/*');
  339. }
  340. /**
  341. * Go to config section action
  342. * @return void
  343. */
  344. protected function _configAction()
  345. {
  346. $this->_redirect('admin/system_config/edit', ['section' => $this->_configSection()]);
  347. }
  348. /**
  349. * Set form data
  350. * @return $this
  351. */
  352. protected function _setFormData($data = null)
  353. {
  354. $this->_getSession()->setData($this->_formSessionKey,
  355. is_null($data) ? $this->getRequest()->getParams() : $data);
  356. return $this;
  357. }
  358. /**
  359. * Get core registry
  360. * @return void
  361. */
  362. protected function _getRegistry()
  363. {
  364. if (is_null($this->_coreRegistry)) {
  365. $this->_coreRegistry = $this->_objectManager->get('\Magento\Framework\Registry');
  366. }
  367. return $this->_coreRegistry;
  368. }
  369. /**
  370. * Check is allowed access
  371. *
  372. * @return bool
  373. */
  374. protected function _isAllowed()
  375. {
  376. return $this->_authorization->isAllowed($this->_allowedKey);
  377. }
  378. /**
  379. * Retrieve model object
  380. * @return \Magento\Framework\Model\AbstractModel
  381. */
  382. protected function _getModel($load = true)
  383. {
  384. if (is_null($this->_model)) {
  385. $this->_model = $this->_objectManager->create($this->_modelClass);
  386. $id = (int)$this->getRequest()->getParam($this->_idKey);
  387. if ($id && $load) {
  388. $this->_model->load($id);
  389. }
  390. }
  391. return $this->_model;
  392. }
  393. }