Magento2 – Get Simple Product ID from Configurable Attribute ID and Value

configurable-productmagento2product-attributesimple-product

I have configure product id 2671

And selected attributes with value

  • attributes id 280[color] and selected value 142[Black]
  • attributes id 757[size] and selected value 181[M]

Based on these values how can I get simple product id of above selected attributes ids and values.

Best Answer

The following code works for me.

<script type="text/javascript">
require(['jquery','underscore'], function(jQuery,_){
    var confProductId = jQuery('.price-box').attr('data-product-id');
    jQuery(".product-options-wrapper select[id^='attribute']").on('change', function() {
        var data = [];
        var $el=jQuery(".product-options-wrapper select[id^='attribute']");
        $el.each(function(){
            data.push({selectedValue:jQuery(this).val(),selectedAttributeId:jQuery(this).attr('id').replace('attribute', '')});
        });
        jQuery.ajax({
            url: "<?php echo $block->getBaseUrl();?>/getweekprice/index/index",
            type: "POST",
            data: { confProductId:confProductId,params: data },
            showLoader: false,
            cache: false,
            success: function(response){
                jQuery('#product-detail-week-prices').html(response).append("<span class='day-text week-text'>per week (ex.VAT)</span>");
            }
        });

    });
});

Custom Module for handling ajax code.

class Index extends \Magento\Framework\App\Action\Action {

protected $resultPageFactory;
protected $jsonHelper;
protected $productObj;
protected $configurableProTypeModel;
protected $logger;
protected $currency;
/**
 * Constructor
 *
 * @param \Magento\Framework\App\Action\Context  $context
 * @param \Magento\Framework\Json\Helper\Data $jsonHelper
 */
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurableProTypeModel,
    \Magento\Catalog\Model\ProductRepository $productRepository,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory,
    \Magento\Framework\Json\Helper\Data $jsonHelper,
    \Magento\Framework\Pricing\Helper\Data $currency,
    \Confproducts\Weekpricesimpleprod\Logger\Logger $logger
) {
    $this->resultPageFactory = $resultPageFactory;
    $this->jsonHelper = $jsonHelper;
    $this->configurableProTypeModel = $configurableProTypeModel;
    $this->productObj = $productRepository;
    $this->logger = $logger;
    $this->currency = $currency;
    parent::__construct($context);
}

/**
 * Execute view action
 *
 * @return \Magento\Framework\Controller\ResultInterface
 */
public function execute()
{
    try {
        $attributesInfo = array();
        $getAjaxPostValues = $this->getRequest()->getPostValue();
        $product = $this->productObj->getById( $getAjaxPostValues['confProductId'] );

        foreach( $getAjaxPostValues['params'] as $attributeData ) {

            if( empty( $attributeData['selectedValue'] ) )
            {
                return $this->jsonResponse( $this->currency->currency(0.00,true, false ) );
            }
             $attributesInfo[$attributeData['selectedAttributeId']] =  $attributeData['selectedValue'];
        }

        $associateProduct = $this->configurableProTypeModel->getProductByAttributes($attributesInfo, $product);
        $getWeekPrice = $associateProduct->getData('week_price');
        $weekPrice =  round( $getWeekPrice,2 );
        $formattedWeekPrice = $this->currency->currency( $weekPrice,true,false);
       // $this->logger->log(100,print_r($getAjaxPostValues,true));
        return $this->jsonResponse( $formattedWeekPrice );
    } catch (\Magento\Framework\Exception\LocalizedException $e) {
        return $this->jsonResponse($e->getMessage());
    } catch (\Exception $e) {
        $this->logger->critical($e);
        return $this->jsonResponse($e->getMessage());
    }
}

/**
 * Create json response
 *
 * @return \Magento\Framework\Controller\ResultInterface
 */
public function jsonResponse($response = '')
{
    return $this->getResponse()->representJson(
        $this->jsonHelper->jsonEncode($response)
    );
}}