0

I am trying to override Magento\Wishlist\Controller\Index\Add controller's execute() method to return a JSON response.

I have created a after plugin for it.

Vendor\Company\etc\frontend\di.xml:

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  <type name="Magento\Wishlist\Controller\Index\Add">
    <plugin name="vendorCompanyExtension" type="Vendor\Company\Plugin\Index\Add" sortOrder="10" disabled="false"/>
  </type>
</config>

Vendor\Company\Plugin\Index\Add.php:

<?php

namespace Vendor\Company\Plugin\Index;

class Add 
{
    /**
     * @var \Magento\Framework\Json\Helper\Data
     */
    protected $_jsonHelper;

    public function __construct(
        \Magento\Framework\Json\Helper\Data $jsonHelper
    ) {
        $this->_jsonHelper = $jsonHelper;
    }

    public function afterExecute(\Magento\Wishlist\Controller\Index\Add $subject, $result) 
    {

        $newResult = [];

        $newResult["message"] = "Hello";

        $subject->getResponse()->representJson(
            $this->_jsonHelper->jsonEncode($newResult)
        );

        return $result;

    }
}

In the original Magento\Wishlist\Controller\Index\Add.php, there is a code:

$resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]);
        return $resultRedirect;

I am trying to return a JSON response instead of redirecting to a Wishlist page after a product is added to the wishlist.

Any help would be appreciated.

1

Try this:

class Add
{
    /** @var \Magento\Framework\Controller\Result\JsonFactory */
    protected $_jsonFactory;

    /**
     * @param \Magento\Framework\Controller\Result\JsonFactory $jsonFactory
     */
    public function __construct(
        \Magento\Framework\Controller\Result\JsonFactory $jsonFactory
    ) {
        $this->_jsonFactory = $jsonFactory;
    }

    /**
     * @param \Magento\Wishlist\Controller\Index\Add $subject
     * @param \Magento\Framework\Controller\Result\Redirect $result
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function afterExecute(
        \Magento\Wishlist\Controller\Index\Add $subject,
        \Magento\Framework\Controller\Result\Redirect $result
    ) {
        return $this->_jsonFactory->create()->setData(['message' => 'Hello']);
    }
}

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.