Magento – “Add to wishlist” without redirecting to wishlist page Magento 2.06

magento2wishlist

I need to add to wishlist ajax based or customer should not redirect to wishlist page with out redirect in Magento 2 environment.

anyone have suggestion please share.

Best Answer

To fix it we need to override Magento\Wishlist\Controller\Index\Add controller.

– add following line in module di.xml to tell magento to use our class instead of standard one.

Filename: Vendor/Module/etc/frontend/di.xml

<preference for="Magento\Wishlist\Controller\Index\Add" type="Vendor\Module\Controller\Index\Add">
</preference>

– create the class. Basically it duplicate original method, only $resultRedirect updated to use referer url

Filename: Vendor/Module/Controller/Index/Add.php

<?php
 
namespace Vendor\Module\Controller\Index;
 
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Action;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Exception\NotFoundException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Controller\ResultFactory;
 
/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Add extends \Magento\Wishlist\Controller\Index\Add
{
    /**
     * Adding new item
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     * @throws NotFoundException
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */
    public function execute()
    {
        ...
        /* here comes the code from original controller  */
        ...
 
        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;
    }
}
Related Topic