Skip to content

Magento2.4 How to override MagentoCheckoutControllerCart?

Even if I simply copy the file without changes, it does not work as a preference. Any idea why?

I created a preference in 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="MagentoCheckoutControllerCartAdd" type="MycompanyMyappControllerCartAdd" />
</config>

I am simply trying to force adding a product to the cart with static data. The same code works in the core file “vendor/magento/module-checkout/Controller/Cart/Add.php”, but does not work in “Mycompany/Myapp/Controller/Cart/Add.php”. It causes the page to redirect to product 4.

Core File: works fine

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace MagentoCheckoutControllerCart;

use MagentoFrameworkAppActionHttpPostActionInterface as HttpPostActionInterface;
use MagentoCatalogApiProductRepositoryInterface;
use MagentoCheckoutModelCart as CustomerCart;
use MagentoFrameworkAppResponseInterface;
use MagentoFrameworkControllerResultInterface;
use MagentoFrameworkExceptionNoSuchEntityException;

/**
 * Controller for processing add to cart action.
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Add extends MagentoCheckoutControllerCart implements HttpPostActionInterface
{
    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @param MagentoFrameworkAppActionContext $context
     * @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
     * @param MagentoCheckoutModelSession $checkoutSession
     * @param MagentoStoreModelStoreManagerInterface $storeManager
     * @param MagentoFrameworkDataFormFormKeyValidator $formKeyValidator
     * @param CustomerCart $cart
     * @param ProductRepositoryInterface $productRepository
     * @codeCoverageIgnore
     */
    public function __construct(
        MagentoFrameworkAppActionContext $context,
        MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
        MagentoCheckoutModelSession $checkoutSession,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoFrameworkDataFormFormKeyValidator $formKeyValidator,
        CustomerCart $cart,
        ProductRepositoryInterface $productRepository
    ) {
        parent::__construct(
            $context,
            $scopeConfig,
            $checkoutSession,
            $storeManager,
            $formKeyValidator,
            $cart
        );
        $this->productRepository = $productRepository;
    }

    /**
     * Initialize product instance from request data
     *
     * @return MagentoCatalogModelProduct|false
     */
    protected function _initProduct()
    {
        $productId = (int)$this->getRequest()->getParam('product');
        
        $productId = (string)"4";
        
        
        if ($productId) {
            $storeId = $this->_objectManager->get(
                MagentoStoreModelStoreManagerInterface::class
            )->getStore()->getId();
            try {
                return $this->productRepository->getById($productId, false, $storeId);
            } catch (NoSuchEntityException $e) {
                return false;
            }
        }
        return false;
    }

    /**
     * Add product to shopping cart action
     *
     * @return ResponseInterface|ResultInterface
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function execute()
    {
        if (!$this->_formKeyValidator->validate($this->getRequest())) {
            $this->messageManager->addErrorMessage(
                __('Your session has expired')
            );
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }

        $paramsOrig = $this->getRequest()->getParams();
        
        
        $params = [];
        $params['uenc'] = $paramsOrig['uenc'];
        $params['product']= "4";
        $params['selected_configurable_option'] = "";
        $params['related_product'] = "";
        $params['item'] = '4';
        $params['form_key'] = $paramsOrig['form_key'];
        $arr[2] = '3';
        $params['options'] = $arr;
        $params['qty'] = '1';

        
        
        
        try {
            if (isset($params['qty'])) {
                $filter = new Zend_Filter_LocalizedToNormalized(
                    ['locale' => $this->_objectManager->get(
                        MagentoFrameworkLocaleResolverInterface::class
                    )->getLocale()]
                );
                $params['qty'] = $filter->filter($params['qty']);
            }

            $product = $this->_initProduct();
            $related = $this->getRequest()->getParam('related_product');

            /** Check product availability */
            if (!$product) {
                return $this->goBack();
            }

            $this->cart->addProduct($product, $params);
            if (!empty($related)) {
                $this->cart->addProductsByIds(explode(',', $related));
            }
            $this->cart->save();

            /**
             * @todo remove wishlist observer MagentoWishlistObserverAddToCart
             */
            $this->_eventManager->dispatch(
                'checkout_cart_add_product_complete',
                ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
            );

            if (!$this->_checkoutSession->getNoCartRedirect(true)) {
                if ($this->shouldRedirectToCart()) {
                    $message = __(
                        'You added %1 to your shopping cart.',
                        $product->getName()
                    );
                    $this->messageManager->addSuccessMessage($message);
                } else {
                    $this->messageManager->addComplexSuccessMessage(
                        'addCartSuccessMessage',
                        [
                            'product_name' => $product->getName(),
                            'cart_url' => $this->getCartUrl(),
                        ]
                    );
                }
                if ($this->cart->getQuote()->getHasError()) {
                    $errors = $this->cart->getQuote()->getErrors();
                    foreach ($errors as $error) {
                        $this->messageManager->addErrorMessage($error->getText());
                    }
                }
                return $this->goBack(null, $product);
            }
        } catch (MagentoFrameworkExceptionLocalizedException $e) {
            if ($this->_checkoutSession->getUseNotice(true)) {
                $this->messageManager->addNoticeMessage(
                    $this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($e->getMessage())
                );
            } else {
                $messages = array_unique(explode("n", $e->getMessage()));
                foreach ($messages as $message) {
                    $this->messageManager->addErrorMessage(
                        $this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($message)
                    );
                }
            }

            $url = $this->_checkoutSession->getRedirectUrl(true);
            if (!$url) {
                $url = $this->_redirect->getRedirectUrl($this->getCartUrl());
            }

            return $this->goBack($url);
        } catch (Exception $e) {
            $this->messageManager->addExceptionMessage(
                $e,
                __('We can't add this item to your shopping cart right now.')
            );
            $this->_objectManager->get(PsrLogLoggerInterface::class)->critical($e);
            return $this->goBack();
        }

        return $this->getResponse();
    }

    /**
     * Resolve response
     *
     * @param string $backUrl
     * @param MagentoCatalogModelProduct $product
     * @return ResponseInterface|ResultInterface
     */
    protected function goBack($backUrl = null, $product = null)
    {
        if (!$this->getRequest()->isAjax()) {
            return parent::_goBack($backUrl);
        }

        $result = [];

        if ($backUrl || $backUrl = $this->getBackUrl()) {
            $result['backUrl'] = $backUrl;
        } else {
            if ($product && !$product->getIsSalable()) {
                $result['product'] = [
                    'statusText' => __('Out of stock')
                ];
            }
        }

        $this->getResponse()->representJson(
            $this->_objectManager->get(MagentoFrameworkJsonHelperData::class)->jsonEncode($result)
        );

        return $this->getResponse();
    }

    /**
     * Returns cart url
     *
     * @return string
     */
    private function getCartUrl()
    {
        return $this->_url->getUrl('checkout/cart', ['_secure' => true]);
    }

    /**
     * Is redirect should be performed after the product was added to cart.
     *
     * @return bool
     */
    private function shouldRedirectToCart()
    {
        return $this->_scopeConfig->isSetFlag(
            'checkout/cart/redirect_to_cart',
            MagentoStoreModelScopeInterface::SCOPE_STORE
        );
    }
}

Preference File: Not Working!

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace MycompanyMyappControllerCart;

use MagentoFrameworkAppActionHttpPostActionInterface as HttpPostActionInterface;
use MagentoCatalogApiProductRepositoryInterface;
use MagentoCheckoutModelCart as CustomerCart;
use MagentoFrameworkAppResponseInterface;
use MagentoFrameworkControllerResultInterface;
use MagentoFrameworkExceptionNoSuchEntityException;

/**
 * Controller for processing add to cart action.
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Add extends MagentoCheckoutControllerCart implements HttpPostActionInterface
{
    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @param MagentoFrameworkAppActionContext $context
     * @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
     * @param MagentoCheckoutModelSession $checkoutSession
     * @param MagentoStoreModelStoreManagerInterface $storeManager
     * @param MagentoFrameworkDataFormFormKeyValidator $formKeyValidator
     * @param CustomerCart $cart
     * @param ProductRepositoryInterface $productRepository
     * @codeCoverageIgnore
     */
    public function __construct(
        MagentoFrameworkAppActionContext $context,
        MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
        MagentoCheckoutModelSession $checkoutSession,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoFrameworkDataFormFormKeyValidator $formKeyValidator,
        CustomerCart $cart,
        ProductRepositoryInterface $productRepository
    ) {
        parent::__construct(
            $context,
            $scopeConfig,
            $checkoutSession,
            $storeManager,
            $formKeyValidator,
            $cart
        );
        $this->productRepository = $productRepository;
    }

    /**
     * Initialize product instance from request data
     *
     * @return MagentoCatalogModelProduct|false
     */
    protected function _initProduct()
    {
        $productId = (int)$this->getRequest()->getParam('product');
        
        $productId = (string)"4";
        
        
        if ($productId) {
            $storeId = $this->_objectManager->get(
                MagentoStoreModelStoreManagerInterface::class
            )->getStore()->getId();
            try {
                return $this->productRepository->getById($productId, false, $storeId);
            } catch (NoSuchEntityException $e) {
                return false;
            }
        }
        return false;
    }

    /**
     * Add product to shopping cart action
     *
     * @return ResponseInterface|ResultInterface
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function execute()
    {
        if (!$this->_formKeyValidator->validate($this->getRequest())) {
            $this->messageManager->addErrorMessage(
                __('Your session has expired')
            );
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }

        $paramsOrig = $this->getRequest()->getParams();
        
        
        $params = [];
        $params['uenc'] = $paramsOrig['uenc'];
        $params['product']= "4";
        $params['selected_configurable_option'] = "";
        $params['related_product'] = "";
        $params['item'] = '4';
        $params['form_key'] = $paramsOrig['form_key'];
        $arr[2] = '3';
        $params['options'] = $arr;
        $params['qty'] = '1';

        
        
        
        try {
            if (isset($params['qty'])) {
                $filter = new Zend_Filter_LocalizedToNormalized(
                    ['locale' => $this->_objectManager->get(
                        MagentoFrameworkLocaleResolverInterface::class
                    )->getLocale()]
                );
                $params['qty'] = $filter->filter($params['qty']);
            }

            $product = $this->_initProduct();
            $related = $this->getRequest()->getParam('related_product');

            /** Check product availability */
            if (!$product) {
                return $this->goBack();
            }

            $this->cart->addProduct($product, $params);
            if (!empty($related)) {
                $this->cart->addProductsByIds(explode(',', $related));
            }
            $this->cart->save();

            /**
             * @todo remove wishlist observer MagentoWishlistObserverAddToCart
             */
            $this->_eventManager->dispatch(
                'checkout_cart_add_product_complete',
                ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
            );

            if (!$this->_checkoutSession->getNoCartRedirect(true)) {
                if ($this->shouldRedirectToCart()) {
                    $message = __(
                        'You added %1 to your shopping cart.',
                        $product->getName()
                    );
                    $this->messageManager->addSuccessMessage($message);
                } else {
                    $this->messageManager->addComplexSuccessMessage(
                        'addCartSuccessMessage',
                        [
                            'product_name' => $product->getName(),
                            'cart_url' => $this->getCartUrl(),
                        ]
                    );
                }
                if ($this->cart->getQuote()->getHasError()) {
                    $errors = $this->cart->getQuote()->getErrors();
                    foreach ($errors as $error) {
                        $this->messageManager->addErrorMessage($error->getText());
                    }
                }
                return $this->goBack(null, $product);
            }
        } catch (MagentoFrameworkExceptionLocalizedException $e) {
            if ($this->_checkoutSession->getUseNotice(true)) {
                $this->messageManager->addNoticeMessage(
                    $this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($e->getMessage())
                );
            } else {
                $messages = array_unique(explode("n", $e->getMessage()));
                foreach ($messages as $message) {
                    $this->messageManager->addErrorMessage(
                        $this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($message)
                    );
                }
            }

            $url = $this->_checkoutSession->getRedirectUrl(true);
            if (!$url) {
                $url = $this->_redirect->getRedirectUrl($this->getCartUrl());
            }

            return $this->goBack($url);
        } catch (Exception $e) {
            $this->messageManager->addExceptionMessage(
                $e,
                __('We can't add this item to your shopping cart right now.')
            );
            $this->_objectManager->get(PsrLogLoggerInterface::class)->critical($e);
            return $this->goBack();
        }

        return $this->getResponse();
    }

    /**
     * Resolve response
     *
     * @param string $backUrl
     * @param MagentoCatalogModelProduct $product
     * @return ResponseInterface|ResultInterface
     */
    protected function goBack($backUrl = null, $product = null)
    {
        if (!$this->getRequest()->isAjax()) {
            return parent::_goBack($backUrl);
        }

        $result = [];

        if ($backUrl || $backUrl = $this->getBackUrl()) {
            $result['backUrl'] = $backUrl;
        } else {
            if ($product && !$product->getIsSalable()) {
                $result['product'] = [
                    'statusText' => __('Out of stock')
                ];
            }
        }

        $this->getResponse()->representJson(
            $this->_objectManager->get(MagentoFrameworkJsonHelperData::class)->jsonEncode($result)
        );

        return $this->getResponse();
    }

    /**
     * Returns cart url
     *
     * @return string
     */
    private function getCartUrl()
    {
        return $this->_url->getUrl('checkout/cart', ['_secure' => true]);
    }

    /**
     * Is redirect should be performed after the product was added to cart.
     *
     * @return bool
     */
    private function shouldRedirectToCart()
    {
        return $this->_scopeConfig->isSetFlag(
            'checkout/cart/redirect_to_cart',
            MagentoStoreModelScopeInterface::SCOPE_STORE
        );
    }
}