Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Post.php
Go to the documentation of this file.
1 <?php
7 
8 use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
12 
13 class Post extends ProductController implements HttpPostActionInterface
14 {
22  public function execute()
23  {
25  $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
26  if (!$this->formKeyValidator->validate($this->getRequest())) {
27  $resultRedirect->setUrl($this->_redirect->getRefererUrl());
28  return $resultRedirect;
29  }
30 
31  $data = $this->reviewSession->getFormData(true);
32  if ($data) {
33  $rating = [];
34  if (isset($data['ratings']) && is_array($data['ratings'])) {
35  $rating = $data['ratings'];
36  }
37  } else {
38  $data = $this->getRequest()->getPostValue();
39  $rating = $this->getRequest()->getParam('ratings', []);
40  }
41  if (($product = $this->initProduct()) && !empty($data)) {
43  $review = $this->reviewFactory->create()->setData($data);
44  $review->unsetData('review_id');
45 
46  $validate = $review->validate();
47  if ($validate === true) {
48  try {
49  $review->setEntityId($review->getEntityIdByCode(Review::ENTITY_PRODUCT_CODE))
50  ->setEntityPkValue($product->getId())
51  ->setStatusId(Review::STATUS_PENDING)
52  ->setCustomerId($this->customerSession->getCustomerId())
53  ->setStoreId($this->storeManager->getStore()->getId())
54  ->setStores([$this->storeManager->getStore()->getId()])
55  ->save();
56 
57  foreach ($rating as $ratingId => $optionId) {
58  $this->ratingFactory->create()
59  ->setRatingId($ratingId)
60  ->setReviewId($review->getId())
61  ->setCustomerId($this->customerSession->getCustomerId())
62  ->addOptionVote($optionId, $product->getId());
63  }
64 
65  $review->aggregate();
66  $this->messageManager->addSuccess(__('You submitted your review for moderation.'));
67  } catch (\Exception $e) {
68  $this->reviewSession->setFormData($data);
69  $this->messageManager->addError(__('We can\'t post your review right now.'));
70  }
71  } else {
72  $this->reviewSession->setFormData($data);
73  if (is_array($validate)) {
74  foreach ($validate as $errorMessage) {
75  $this->messageManager->addError($errorMessage);
76  }
77  } else {
78  $this->messageManager->addError(__('We can\'t post your review right now.'));
79  }
80  }
81  }
82  $redirectUrl = $this->reviewSession->getRedirectUrl(true);
83  $resultRedirect->setUrl($redirectUrl ?: $this->_redirect->getRedirectUrl());
84  return $resultRedirect;
85  }
86 }
_redirect($path, $arguments=[])
Definition: Action.php:167
__()
Definition: __.php:13
$rating
Definition: item.phtml:18
Definition: Post.php:13