Magento 2 – How to Add Simple Product to Cart Instead of Configurable Product

addtocartconfigurable-productmagento2pluginsimple-product

I would like to add the simple product equivalent of the selected configurable product to the cart.
I would like to solve that with a plugin.
I would like to know where should I intercept the code, and how can I get the simple product if I have the configurable product with the selected attributes.

So what I did until now:

class Cart
{

protected $quote;
protected $request;
protected $configurableproduct;

public function __construct(
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Framework\App\Request\Http $request,
    \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurableproduct
){
    $this->quote = $checkoutSession->getQuote();
    $this->request = $request;
    $this->configurableproduct = $configurableproduct;
}

public function beforeAddProduct($subject, $productInfo, $requestInfo = null)
{

    $paramsData = $this->request->getParams();
    foreach($paramsData as $pId=>$param){ echo "booo";
            $params['product'] = $paramsData['product'][$pId];
            $params['super_attribute'] = $paramsData['super_attribute'][$pId];
        }
        var_dump($params);
    }
    $productId = (int)$this->request->getParam('product', 0);


    return array($productInfo, $requestInfo);
}
}

But it does not work…

It must be something with the foreach loop, because if I comment that out, the code runs.

Best Answer

So, this is my solution:

class Cart
{
protected $quote;
protected $request;
protected $configurableproduct;
protected $urlinterface;
protected $productrepository;

public function __construct(
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Framework\App\Request\Http $request,
    \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurableproduct,
    \Magento\Framework\UrlInterface $urlinterface,
    \Magento\Catalog\Model\ProductRepository $productrepository
){
    $this->quote = $checkoutSession->getQuote();
    $this->request = $request;
    $this->configurableproduct = $configurableproduct;
    $this->urlinterface = $urlinterface;
    $this->productrepository = $productrepository;
}

public function beforeAddProduct($subject, $productInfo, $requestInfo = null)
{

    $paramsData = $this->request->getParams();
    $productId = $paramsData['product'];
    $product = $this->productrepository->getById($productId);
    if ($product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
        $attributes = $paramsData['super_attribute'];

        $new_product = $this->configurableproduct->getProductByAttributes($attributes, $product);
        $new_productId = $new_product->getID();

        $productInfo = $new_productId;
    }

    return array($productInfo, $requestInfo);
}
}