magento 2 getting product data from wishlist

by Naberd Zendi   Last Updated April 15, 2019 11:09 AM

Coming in to trouble while getting correct data from my wishlist:

/** 
    @var \Magento\Wishlist\Model\Wishlist $_wishlist 
    @var \Magento\Customer\Model\Session $_customerSession
*/
$wishlistCollection = $this->_wishlist->loadByCustomerId($this->_customerSession->getCustomerId(), true)->getItemCollection();
foreach($wishlistCollection as $wishedItem){
    /** @var \Magento\Catalog\Model\Product $_product; */
    $product = $this->_product->setStoreId($wishedItem->getStoreId())->load($wishedItem->getProductId);
    /** @var \Magento\Review\Model\Rating $_rating; */
    $rating = $this->_rating->getEntitySummary($wishedItem->getProductId(), true);
    $ratingValue = NULL;
    if($rating->getSum() && $rating->getCount()) $ratingValue = $rating->getSum()/$rating->getCount();

    echo $product->getName();
    echo $product->getSku();
    echo $product->getProductUrl();
    echo $ratingValue;
}

product 1 was clone of the original product. Product 1 has rating while original has no reviews.Review to product 1 was added after dublicating.

while in the loop product name and sku are different, but url and rating values are the same, so not sure what is wrong here.



Answers 1


Your way to load products reuses the same product model. In that way you will have data of the previous product in cases in which the new product for example does not a have data for a specific attribute.

You should use a product factory instead for loading the product in the following way:

protected $_productFactory;

//inject product factory in constructor
public function __construct(
    [...]
    \Magento\Catalog\Model\ProductFactory $productFactory
    )
   {
       [...]
       $this->_productFactory = $productFactory;
   }

   [...]
   //load product
   $product = $this->_productFactory->create()->setStoreId($wishedItem->getStoreId())->load($wishedItem->getProductId);

Or at least call reset() on your product model before loading a new product:

   $product = $this->_product->reset()->setStoreId($wishedItem->getStoreId())->load($wishedItem->getProductId);
HelgeB
HelgeB
April 15, 2019 11:00 AM

Related Questions



Magento 2 remove items from wishlist

Updated April 25, 2016 08:03 AM

Wishlist Module copy, Edit link not working

Updated March 09, 2017 11:09 AM

Magento 2 - Keep Wishlist items

Updated July 05, 2016 08:04 AM