0

How to get a simple product id from configurable option in magento 2

enter image description here

0

You have to override block:

app/code/Custom/Coreoverride/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\Swatches\Block\Product\Renderer\Configurable" type="Custom\Coreoverride\Block\Swatches\Product\Renderer\Configurable"/>
</config>

app/code/Custom/Coreoverride/Block/ConfigurableProduct/Product/View/Type/Configurable.php

    <?php

namespace Custom\Coreoverride\Block\ConfigurableProduct\Product\View\Type;

use Magento\Framework\Json\EncoderInterface;
use Magento\Framework\Json\DecoderInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;

/**
 * Class Configurable
 *
 * @package Custom\Coreoverride\Block\ConfigurableProduct\Product\View\Type
 */
class Configurable
{
    /**
     * @var EncoderInterface
     */
    protected $jsonEncoder;

    /**
     * @var DecoderInterface
     */
    protected $jsonDecoder;

    /**
     * @var StockRegistryInterface
     */
    protected $stockRegistry;

    /**
     * Configurable constructor.
     * @param EncoderInterface $jsonEncoder
     * @param DecoderInterface $jsonDecoder
     * @param StockRegistryInterface $stockRegistry
     */
    public function __construct(
        EncoderInterface $jsonEncoder,
        DecoderInterface $jsonDecoder,
        StockRegistryInterface $stockRegistry
    ) {
        $this->jsonDecoder = $jsonDecoder;
        $this->jsonEncoder = $jsonEncoder;
        $this->stockRegistry = $stockRegistry;
    }

    /**
     * backorders status, backorders time period
     *
     * @param \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable $subject
     * @param \Closure $proceed
     * @return array
     */
    public function aroundGetJsonConfig(
        \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable $subject,
        \Closure $proceed
    )
    {
        $config = $proceed();
        $config = $this->jsonDecoder->decode($config);
        foreach ($subject->getAllowProducts() as $product) {
                echo $product->getId();
        }
        return $this->jsonEncoder->encode($config);
    }
}
  • How to get a configurable product id in addtocart template file – divya sekar May 21 at 8:55

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.