Customer Experience Insights - LATAM

Cómo interactuar con el wish list de un cliente en Magento 2

Escrito por Christopher Liddell | 08 17, 2022

La lista de deseos del cliente es una herramienta importante para ofrecer una mejor experiencia de usuario, aumentar ventar y obtener más datos del cliente para poder modelar y analizar sus preferencias.

En Magento 2, se puede obtener y modificar el wish list del cliente en el backend de la siguiente manera:

<?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;
  }
}

 

Las funciones en la clase anterior sirven para lo siguiente:

  • getCustomerId():  Obtiene el #id del cliente de la sesión actual. Este comportamiento se puede reemplazar según cómo se quiere seleccionar al cliente. 
  • isInWishlist($productId):  Averigua si el producto con el #id especificado se encuentra en el wishlist de deseos.
  • addProductToWishlist($productId):  Agrega el producto con el #id especificado a la lista de deseos del cliente.
  • removeProductFromWishlist($productId) Elimina el producto con el #id especificado de la lista de deseos del cliente.


También es posible visualizar la información del wish list del cliente en el frontend con javascript de las siguientes  maneras:

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

var items = wishlist.items;




O bien, utilizando como base el código de:

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');
    }
  });
});

Adicionalmente, si quieres crear un botón para agregar productos al wish list, puedes hacerlo en tu plantilla (ej:  Magento_Catalog/templates/products/list/addto/wishlist.phtml ) con el siguiente código:

<?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();
?>

Espero que este artículo haya sido de utilidad para crear componentes que interactúan con la lista de deseos del cliente.