Add Product Rating and Reviews in Magento2
Add This Code in Controller Or Use in Phtml
<?php namespace Custom\Module\Controller\Index; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; class Productrating extends \Magento\Framework\App\Action\Action { public function __construct( Context $context, \Magento\Review\Model\ReviewFactory $reviewFactory, \Magento\Review\Model\RatingFactory $ratingFactory, \Magento\Store\Model\StoreManagerInterface $storeManager ) { parent::__construct($context); $this->_reviewFactory = $reviewFactory; $this->_ratingFactory = $ratingFactory; $this->_storeManager = $storeManager; } public function execute() { $productid = 201;//product id you set accordingly $reviewdata['ratings'][1] = 5; //Rating First $reviewdata['ratings'][2] =4; //Rating Second $reviewdata['ratings'][3] =3; //Rating THird $reviewdata['nickname'] = "jhon"; //Name $reviewdata['title'] = "product is too good"; //Title $reviewdata['detail'] ="product is too good product is too good product is too good"; //Content $review = $this->_reviewFactory->create()->setData($reviewdata); $review->unsetData('review_id'); $review->setEntityId($review->getEntityIdByCode(\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE)) ->setEntityPkValue($productid) ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED)//By default set approved ->setStoreId($this->_storeManager->getStore()->getId()) ->setStores([$this->_storeManager->getStore()->getId()]) ->save(); foreach ($reviewdata['ratings'] as $ratingId => $optionId) { $this->_ratingFactory->create() ->setRatingId($ratingId) ->setReviewId($review->getId()) ->addOptionVote($optionId, $productid); } $review->aggregate(); echo "Rating and Feedback sucessfully Submitted";echo "<br>"; echo "Rating will shown in the product detail Page"; } } |
Comments
Post a Comment