How To

Magento 2: Get Simple Product from Configurable Product before Add to Cart

Hello Magento Friends,

Today I am here with a solution for Magento 2: Get Simple Product from Configurable Product before Add to Cart.

A configurable product is a set of simple products that can be bought together or separately. You can Create Configurable Product Programmatically in Magento 2.

When working with configurable products, you need to check simple product attributes with the products already in the cart in order to determine whether to add them to the shopping cart or not. For this, you need to get the simple product from the configurable product before adding it to the cart in Magento 2.

Let’s learn the steps for How to Get Simple Product from Configurable Product before Add to Cart in Magento 2.

Steps to Get Simple Product from Configurable Product before Add to Cart in Magento 2:

Step 1: Go to the below file Path

app\code\Vendor\Extension\etc\events.xml

Now, add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_checkout_cart_add">
        <observer name="simple_product_cart_add_before" instance="Vendor\Extension\Observer\Cartadd"/>
    </event>
</config>

Step 2: Next move to the following file path

app\code\Vendor\Extension\Observer\Cartadd.php

And add the code as mentioned below

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Response\RedirectInterface;
use Magento\Checkout\Model\Cart;
use Magento\Framework\App\RequestInterface;
use Magento\Catalog\Model\Product;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;

class Cartadd implements ObserverInterface
{
     protected $cart;
     protected $redirect;
     protected $request;
     protected $product;
     protected $configurableproduct;

     public function __construct(
     RedirectInterface $redirect, 
     Cart $cart,  
     RequestInterface $request, 
     Product $product, 
     Configurable $configurableproduct)
     {
          $this->redirect = $redirect;
          $this->cart = $cart;
          $this->request = $request;
          $this->product = $product;
          $this->configurableproduct = $configurableproduct;
     }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
         $postValues = $this->request->getPostValue();
         $productId = $postValues['product'];
         $addProduct = $this->product->load($productId);
         
         if ($addProduct->getTypeId() == \Magento\ConfigurableProduct\Model\Product\ Type\Configurable::TYPE_CODE) 
         {
              $attributes = $postValues['super_attribute'];
              $simple_product = 
              $this->configurableproduct->getProductByAttributes($attributes,  $addProduct);
              echo $simple_product->getID();
         } 
     }
}

Step 3: After completing the above steps, run the below commands

sudo php bin/magento setup:di:compile
sudo php bin/magento cache:flush

Conclusion:

This way you can Get Simple Product from Configurable Product before Add to Cart in Magento 2. Also, check out Magento 2 Sticky Add To Cart extension for displaying an appealing sticky bar and Add to Cart button. For any queries, mention in the comment box without hesitation. See you next time with another solution till then stay with us!

Happy Coding!

Click to rate this post!
[Total: 4 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

17 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

2 days ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

2 days ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

2 weeks ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

2 weeks ago