Skip to content

Passing Configurable URL With Simple Product

I have a module setup for Magento 2.4.6 which replaces the product name of a configurable with the simple product selected.

It replaces this in the minicart & cart. It works fine except that the simple product in cart/minicart no longer links to the listing. I need it to link to the configurable listing as it does in Magento by default.

This is my module code, originally from Magento Community Forum.

Add.php:

namespace SRMagentoStackExchangePluginCheckoutControllerCart;

use MagentoStoreModelStoreManagerInterface;
use MagentoCatalogApiProductRepositoryInterface;
use MagentoFrameworkExceptionNoSuchEntityException;
use MagentoConfigurableProductModelProductTypeConfigurable;

class Add
{
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

    /**
     * @var Configurable
     */
    private $configurable;

    /**
     * Add constructor.
     *
     * @param StoreManagerInterface $storeManager
     * @param ProductRepositoryInterface $productRepository
     * @param Configurable $configurable
     */
    public function __construct(
        StoreManagerInterface $storeManager,
        ProductRepositoryInterface $productRepository,
        Configurable $configurable
    ) {
        $this->productRepository = $productRepository;
        $this->storeManager = $storeManager;
        $this->configurable = $configurable;
    }

    public function aroundExecute(
        MagentoCheckoutControllerCartAdd $subject,
        Closure $proceed
    ) {

        $productId = (int)$subject->getRequest()->getParam('product');
        if ($product = $this->initProduct($productId)) {
            if ($product->getTypeId() == Configurable::TYPE_CODE) {
                $params = $subject->getRequest()->getParams();
                $childProduct = $this->configurable->getProductByAttributes($params['super_attribute'], $product);
                if ($childProduct->getId()) {
                    $params['product'] = $childProduct->getId();
                    $subject->getRequest()->setParams($params);
                }
            }
        }

        return $proceed();
    }

    /**
     * Initialize product instance from request data
     *
     * @return MagentoCatalogModelProduct|false
     */
    protected function initProduct($productId)
    {
        if ($productId) {
            $storeId = $this->storeManager->getStore()->getId();
            try {
                return $this->productRepository->getById($productId, false, $storeId);
            } catch (NoSuchEntityException $e) {
                return false;
            }
        }
        return false;
    }
}