Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Save.php
Go to the documentation of this file.
1 <?php
7 
8 use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
14 
16 {
20  private $queryFactory;
21 
26  public function __construct(
27  Context $context,
28  QueryFactory $queryFactory
29  ) {
30  parent::__construct($context);
31  $this->queryFactory = $queryFactory;
32  }
33 
40  public function execute()
41  {
42  $data = $this->getRequest()->getPostValue();
43  if ($this->getRequest()->isPost() && $data) {
44  try {
45  $model = $this->loadQuery();
46  $model->addData($data);
47  $model->setIsProcessed(0);
48  $model->save();
49  $this->messageManager->addSuccessMessage(__('You saved the search term.'));
50  } catch (LocalizedException $e) {
51  $this->messageManager->addErrorMessage($e->getMessage());
52  return $this->proceedToEdit($data);
53  } catch (\Exception $e) {
54  $this->messageManager->addExceptionMessage(
55  $e,
56  __('Something went wrong while saving the search query.')
57  );
58  return $this->proceedToEdit($data);
59  }
60  }
61 
63  $redirectResult = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
64  return $redirectResult->setPath('search/*');
65  }
66 
73  private function loadQuery()
74  {
75  //validate query
76  $queryText = $this->getRequest()->getPost('query_text', false);
77  $queryId = $this->getRequest()->getPost('query_id', null);
78 
79  /* @var $model \Magento\Search\Model\Query */
80  $model = $this->queryFactory->create();
81  if ($queryText) {
82  $storeId = $this->getRequest()->getPost('store_id', false);
83  $model->setStoreId($storeId);
84  $model->loadByQueryText($queryText);
85  if ($model->getId() && $model->getId() != $queryId) {
86  throw new \Magento\Framework\Exception\LocalizedException(
87  __('You already have an identical search term query.')
88  );
89  }
90  }
91  if ($queryId && !$model->getId()) {
92  $model->load($queryId);
93  }
94  return $model;
95  }
96 
103  private function proceedToEdit($data)
104  {
105  $this->_getSession()->setPageData($data);
107  $redirectResult = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
108  return $redirectResult->setPath('search/*/edit', ['id' => $this->getRequest()->getPost('query_id', null)]);
109  }
110 }
__()
Definition: __.php:13
__construct(Context $context, QueryFactory $queryFactory)
Definition: Save.php:26