Magento – Get Wishlist product collection in Controller of Custom module Magento2

magento2modulePHPwishlist

I am trying to get Wishlist product collection in Custom module controller for the new functionality. I searched in google and I got this:

Inject this class in your constructor:

protected $wishlistProvider;

public function __construct(
    ...
    \Magento\Wishlist\Controller\WishlistProviderInterface $wishlistProvider
) {
    $this->wishlistProvider = $wishlistProvider;
    ...
}

and

$currentUserWishlist = $this->wishlistProvider->getWishlist();
if ($currentUserWishlist) {
    $wishlistItems = $currentUserWishlist->getItemCollection();
}

I have tried using this code. But its not working. I am getting this error:

Uncaught TypeError: Argument 3 passed to
namespace\modulename\Controller\Index\Index::__construct() must be an
instance of Magento\Wishlist\Controller\WishlistProviderInterface,
none given, called in
/var/www/project_name/var/generation/namespace/modulename/Controller/Index/Index/Interceptor.php
on line 14

Please suggest me a way to do this. Thanks in advance!!

Best Answer

In other way you can get wishlist items collection.

Use factory Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory for getting wishlist product collection and filter that by addCustomerIdFilter($customerId)

protected $_currentUserWishlistCollectionFactory ;
protected $_Customersession;
public function __construct(
       \Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory $currentUserWishlistCollectionFactory,
    \Magento\Customer\Model\Session $Customersession,
    ) {
    ....
    $this->_Customersession = $Customersession;
        $this->_currentUserWishlistCollectionFactory = $currentUserWishlistCollectionFactory;
....

    }

public function getcurrentUserWishlistItems(){

    $collection = $this->_currentUserWishlistCollectionFactory->create();
    $collection->addCustomerIdFilter($this->_Customersession->getCustomerId());
    return $collection;

}
Related Topic