0

What is the best way to override _initProduct() function in:

vendor\magento\module-checkout\Controller\Cart\Add.php

I have this in my di.xml:

<type name="Magento\Checkout\Controller\Cart\Add">
    <plugin name="x_cart_add" type="X\Y\Plugin\Checkout\Controller\Cart\Add" sortOrder="1"/>
</type>

Method:

/**
 * Initialize product instance from request data
 *
 * @return \Magento\Catalog\Model\Product|false
 */
protected function _initProduct()
{
    $productId = (int)$this->getRequest()->getParam('product');
    if ($productId) {
        $storeId = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getId();
        try {
            return $this->productRepository->getById($productId, false, $storeId);
        } catch (NoSuchEntityException $e) {
            return false;
        }
    }
    return false;
}
0

You can take the Magento 2 preference to override, for exmple.

Vendor/Module/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">
    <preference for="Magento\Checkout\Controller\Cart\Add" type="Vendor\Module\Controller\Cart\Add" />
</config>

Vendor\Module\Controller\Cart\Add

namespace Vendor\Module\Controller\Cart;

class Add extends \Magento\Checkout\Controller\Cart\Add
{

    protected function _initProduct()
    {
      // Do necessary action and return to parent.
    }    
}
| improve this answer | |

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.