1

How to change the wishlist button color once the products added to the wishlist.I am getting an error while using a controller.

Ref:

1)https://magento.stackexchange.com/a/256570/57334

2)https://magento.stackexchange.com/a/266125/57334 (Controller)

13
1

Using a custom controller to change Wishlist button(icon) color once the product added to Wishlist.

app/code/vendor/module/Controller/Index/Wishlist.php

<?php 
namespace Vendor\Module\Controller\Index;

class Wishlist extends \Magento\Framework\App\Action\Action {

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Wishlist\Helper\Data $wishlistHelper,
        \Magento\Framework\Controller\Result\JsonFactory $jsonFactory
        ) {
            parent::__construct($context);
            $this->wishlistHelper = $wishlistHelper;
            $this->jsonFactory = $jsonFactory;
    }

    public function execute() {
        $result = $this->jsonFactory->create();
        $data = $this->wishlistHelper->getWishlistItemCollection()->getData();

        return $result->setData(['status' => 200, 'items' => $data]);
    }
}

app/code/vendor/module/etc/frontend/routes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="customwishlist" id="customwishlist">
            <module name="Devcrew_Wishlistcustom"/>
        </route>
    </router>

Add the following Script in theme's list.phtml or wishlist.phtml Depend upon Theme :

 <script>
    require(['jquery'], function($){
    jQuery.ajax({
    url: '<?php echo $this->getUrl('customwishlist/index/wishlist') ?>',
    method: 'get',
    dataType: 'json',
    success: function(data) {
    var wislistAddesCheckData = data;
    var itemLenth = wislistAddesCheckData.items.length;
    for(i=0;i<itemLenth; i++){
    var wislistAddedProductId = wislistAddesCheckData.items[i].product_id;
    $(".product-id-"+wislistAddedProductId).attr('src','<?php echo $img; ?>');
    }
    }
    });
    });
    </script>

Add this class in wishlist Div or Image:

class="product-id-<?php echo $block->getProduct()->getId();?>"
2
  • Thank you, working perfectly. – zus Feb 17 at 9:58
  • Hi Hafiz Arslan, If customer click Wishlist icon the products added to wishlist also changed the wishlist icon color, now i want how to remove if customer click wishlist again, any help thanks. can u pls join the chat chat.stackexchange.com/rooms/120695/… – zus Mar 26 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.