<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=262721675103356&amp;ev=PageView&amp;noscript=1">

1 min read

How to interact with a customer wish list in Magento 2

The customer wishlist is an important tool to offer a better user experience, increase sales and obtain more data from the customer in order to model and analyze their preferences.

In Magento 2, you can get and modify the customer's wishlist programmatically  with the following code:

<?php
namespace Imagineer\Wishlist\Helper;
use \Magento\Framework\App\Helper\AbstractHelper;
use \Magento\Framework\App\Helper\Context;
use \Magento\Customer\Model\Session;
use \Magento\Wishlist\Model\Wishlist;
use \Magento\Catalog\Api\ProductRepositoryInterface;


class WhishlistHelper extends AbstractHelper {
  private $session;
  private $wishlist;
  private $productRepository;


  /**
  * @param \Magento\Framework\App\Helper\Context $context
  * @param \Magento\Wishlist\Model\Wishlist $wishlistHelper
  * @param \Magento\Customer\Model\Session $session
  * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
  */
  public function __construct(
    Context $context,
    Wishlist $wishlist,
    Session $session,
    ProductRepositoryInterface $productRepository

  ) {
    parent::__construct($context);
    $this->wishlist = $wishlist;
    $this->session = $session;
    $this->productRepository = $productRepository;
  }


  public function getCustomerId(){
    if(!$this->session->isLoggedIn()){
      return false;
    }
    return $this->session->getCustomerId();
  }


  public function isInWishlist($productId){
    $customerId = $this->getCustomerId();
    if(!$customerId){
      return false;
    }

    $wishlistCollection = $this->wishlist->loadByCustomerId($customerId)
->getItemCollection();
    $inWishlist = false;
    foreach ($wishlistCollection as $wishlist_item) {
      if($wishlist_item->getProduct()->getId() == $productId){
        $inWishlist = true;
        break;
      }
    }
    return $inWishlist;
  }

  public function addProductToWishlist($productId){
    if(!$this->isInWishlist($productId)){
      return false;
    }

    $product = $this->_productRepository->getById($productId);
if($product == null){
return false;
}
    $wishlist = $this->wishlist->loadByCustomerId($customerId);
$wishlist->addNewItem($product);
$wishlist->save();

  return true;
  }

  public function removeProductFromWishlist($productId){
    if(!$this->isInWishlist($productId)){
      return false;
    }

 
    $product = $this->_productRepository->getById($productId);
if($product == null){
return false;
}
 
    $wishlist = $this->wishlist->loadByCustomerId($customerId);
$items = $wishlist->getItemCollection();
    foreach ($items as $item) {
if ($item->getProductId() == $productId) {
$item->delete();
$wish->save();
}
}

return true;
  }
}

 

The functions in the above class do the following:

  • getCustomerId(): Gets the #id of the current client. This behavior can be overridden depending on how you want to select the client.
  • isInWishlist($productId): Find out if the product with the specified #id is in the wishlist.
  • addProductToWishlist($productId): Adds the product with the specified #id to the customer's wishlist.
  • removeProductFromWishlist($productId): Remove the product with the specified #id from the customer's wishlist.


It is also possible to display the customer's wishlist information in the frontend with javascript in the following ways:

var wishlist = JSON.parse(localStorage.getItem('mage-cache-storage')).wishlist;

var items = wishlist.items;


Wish list information in the frontend_Magento

Or using the following file as a base:

vendor/magento/module-wishlist/view/frontend/web/js/view/wishlist.js

define([
    'uiComponent',
    'Magento_Customer/js/customer-data'
  ], function (Component, customerData) {
  'use strict';

  return Component.extend({
    initialize: function () {
      this._super();
      this.wishlist = customerData.get('wishlist');
    }
  });
});

Additionally, if you want to create a button to add products to the wishlist, you can do it in your template   (such as Magento_Catalog/templates/products/list/addto/wishlist.phtml ) with the following code:

<?php
echo $block->getLayout()
->createBlock('Magento\Wishlist\Block\Catalog\Product\ProductList\Item\AddTo\Wishlist')
->setProduct($_product)
->setTemplate("Magento_Wishlist::catalog/product/list/addto/wishlist.phtml")->toHtml();
?>

I hope this article has been helpful to create components that interact with the customer's wishlist.

 

 

Suggested Insights For You

How to create a simple web API in Magento2

How to create a simple web API in Magento2

Webservices are vital mechanisms for two or more systems to communicate, since they allow information to be transferred, procedures to be executed or...

Read More
How to configure the wishlist in Magento

How to configure the wishlist in Magento

E-commerce platforms offer the functionality to store lists of products that interest users. Also, this helps improve the customer experience by...

Read More
Magento B2B and its Importance in Businesses

Magento B2B and its Importance in Businesses

Because companies must adapt to a digital sales market where platforms such as Magento B2B provide options to manage the massive orders that come in...

Read More

ICX SUBSCRIPTION

Come and be part of the latest specific insights provided by our experts

What’s next?

ARE YOU READY?