How to get simple product id from selected configurable Attribute id and it's value in Magento 2?Get simple product id from configurable product selectionNeed to get Simple Products with Configurable Option from Configurable Productconfigurable product name changes to simple product name when attributes (color/size) are selectedHow to Get Configurable Attributes of a Simple ProductShow/Hide product configurable attributes depending on another attributeMagento : How to get simple products details on configurable product pageProduct name not changing when choosing a simple product from dropdown?Simple Product AttributeGet selected product options on configurable productHow to add default value for attribute of configurable product

Billiard balls collision

Server Integrity Check CheckCommands question

Joining lists with same elements

Can a giant mushroom be used as a material to build watercraft or sailing ships?

What is a natural problem in theory of computation?

How to make onclick function execute only once?

Separating old 2 x 4 brick with wheel holder

Papers on arXiv solving the same problem at the same time

I don't have the theoretical background in my PhD topic. I can't justify getting the degree

Why isn't "I've" a proper response?

How do proponents of Sola Scriptura address the ministry of those Apostles who authored no parts of Scripture?

How is linear momentum conserved in case of a freely falling body?

When calculating a force, why do I get different result when I try to calculate via torque vs via sum of forces at an axis?

Can you cast bonus action and reaction spells while already casting a spell?

To get so rich that you are not in need of anymore money

Immediate Smaller Element Time Limit Exceeded

“T” in subscript in formulas

Why doesn't 'd /= d' throw a division by zero exception?

How to gently end involvement with an online community?

Is gzip atomic?

Why does Windows store Wi-Fi passwords in a reversible format?

Evaluated vs. unevaluated Association

Add 2 new columns to existing dataframe using apply

Why is the UK so keen to remove the "backstop" when their leadership seems to think that no border will be needed in Northern Ireland?



How to get simple product id from selected configurable Attribute id and it's value in Magento 2?


Get simple product id from configurable product selectionNeed to get Simple Products with Configurable Option from Configurable Productconfigurable product name changes to simple product name when attributes (color/size) are selectedHow to Get Configurable Attributes of a Simple ProductShow/Hide product configurable attributes depending on another attributeMagento : How to get simple products details on configurable product pageProduct name not changing when choosing a simple product from dropdown?Simple Product AttributeGet selected product options on configurable productHow to add default value for attribute of configurable product






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















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.










share|improve this question
























  • On attribute select, did you get configurable product id?

    – Rohan Hapani
    Apr 3 at 8:34











  • Yes, configurable product id is 2671

    – Aditya Shah
    Apr 3 at 8:53

















0















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.










share|improve this question
























  • On attribute select, did you get configurable product id?

    – Rohan Hapani
    Apr 3 at 8:34











  • Yes, configurable product id is 2671

    – Aditya Shah
    Apr 3 at 8:53













0












0








0








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.










share|improve this question














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.







magento2 configurable-product product-attribute simple-product






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Apr 3 at 8:27









Aditya ShahAditya Shah

5,1472 gold badges12 silver badges45 bronze badges




5,1472 gold badges12 silver badges45 bronze badges















  • On attribute select, did you get configurable product id?

    – Rohan Hapani
    Apr 3 at 8:34











  • Yes, configurable product id is 2671

    – Aditya Shah
    Apr 3 at 8:53

















  • On attribute select, did you get configurable product id?

    – Rohan Hapani
    Apr 3 at 8:34











  • Yes, configurable product id is 2671

    – Aditya Shah
    Apr 3 at 8:53
















On attribute select, did you get configurable product id?

– Rohan Hapani
Apr 3 at 8:34





On attribute select, did you get configurable product id?

– Rohan Hapani
Apr 3 at 8:34













Yes, configurable product id is 2671

– Aditya Shah
Apr 3 at 8:53





Yes, configurable product id is 2671

– Aditya Shah
Apr 3 at 8:53










4 Answers
4






active

oldest

votes


















2















Magento provides function for that, by passing attributes in array format you can get simple product of those variants.




/magento/module-configurable-product/Model/Product/Type/Configurable.php




  • 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]

Retrieve used product by attribute values



public function __construct(
MagentoConfigurableProductModelProductTypeConfigurable $configurableProTypeModel,
MagentoCatalogModelProduct $product
)
$this->_configurableProTypeModel = $configurableProTypeModel;
$this->_product = $product;


$product = $this->productRepository->getById($product_id);
// Valid format for attributes
//$attributesInfo = array( $attributeId => $attributeValue);
$attributesInfo = array( 280 => 145,757=>181);

$associateProduct = $this->_configurableProTypeModel->getProductByAttributes($attributesInfo, $product);





share|improve this answer
































    1















    You can use this below code to get simple product id based on configurable product ID.



    If you get value of selected configurable product id in js file, then you can pass value using ajax and call controller to get simple product id.
    If you want to get simple product id by compare value of selected attribute value, then you can use commented code also.



    Add this below code in your controller :



    <?php
    namespace RHBlogControllerIndex;

    class Test extends MagentoFrameworkAppActionAction

    /**
    * @var MagentoCatalogApiProductRepositoryInterface
    */
    protected $productRepository;

    /**
    * @var MagentoStoreModelStoreManagerInterface
    */
    protected $storeManager;
    /**
    * [__construct description]
    * @param MagentoCatalogApiProductRepositoryInterface $productRepository [description]
    * @param MagentoStoreModelStoreManagerInterface $storeManager [description]
    */
    public function __construct(
    ....
    MagentoCatalogApiProductRepositoryInterface $productRepository,
    MagentoStoreModelStoreManagerInterface $storeManager
    ....
    )
    ....
    $this->productRepository = $productRepository;
    $this->storeManager = $storeManager;
    ....


    public function execute()
    $configurable_id = '2671';
    $product = $this->productRepository->getById($configurable_id);
    $storeId = $this->storeManager->getStore()->getId();
    $productTypeInstance = $product->getTypeInstance();
    $productTypeInstance->setStoreFilter($storeId, $product);
    $usedProducts = $productTypeInstance->getUsedProducts($product);

    foreach ($usedProducts as $child)
    echo "Simple Product ID : ".$child->getId() . "<br/>";
    // $selected_option_val = $child->getAttributeText('color');
    // if ($selected_option_val == 'your_selected_attr_val')
    // return $child->getId();
    //








    share|improve this answer

























    • Thanks for the answer +1 for the efforts :)

      – Aditya Shah
      Apr 4 at 5:49


















    1















    Try this.



    public function __construct(
    MagentoStoreModelStoreManagerInterface $storeManager,
    MagentoCatalogModelResourceModelEavAttribute $eavAttribute,
    MagentoCatalogModelProductRepository $productRepository
    )
    $this->storeManager = $storeManager;
    $this->eavAttribute = $eavAttribute;
    $this->productRepository = $productRepository;


    public function getSimpleProductId()

    $simple_product_id = null;
    $configurable_product_id = 2671;
    $color_id = 280;
    $size_id = 757;

    $color_value = 142;
    $size_value = 181;

    $color_code = $this->eavAttribute->load($color_id)->getAttributeCode();
    $size_code = $this->eavAttribute->load($size_id)->getAttributeCode();

    $product = $this->getProductById($configurable_product_id);
    $productTypeInstance = $product->getTypeInstance();
    $simple_products = $productTypeInstance->getUsedProducts($product);
    foreach ($simple_products as $simple)

    if($simple->getData($color_code) == $color_value && $simple->getData($size_code) == $size_value)

    $simple_product_id = $simple->getId();



    return $simple_product_id;


    public function getProductById($id)

    return $this->productRepository->getById($id, false, $this->storeManager->getStore()->getId());






    share|improve this answer

























    • Thanks for the answer +1 for the efforts :)

      – Aditya Shah
      Apr 4 at 5:49


















    1















    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 MagentoFrameworkAppActionAction



    protected $resultPageFactory;
    protected $jsonHelper;
    protected $productObj;
    protected $configurableProTypeModel;
    protected $logger;
    protected $currency;
    /**
    * Constructor
    *
    * @param MagentoFrameworkAppActionContext $context
    * @param MagentoFrameworkJsonHelperData $jsonHelper
    */
    public function __construct(
    MagentoFrameworkAppActionContext $context,
    MagentoConfigurableProductModelProductTypeConfigurable $configurableProTypeModel,
    MagentoCatalogModelProductRepository $productRepository,
    MagentoFrameworkViewResultPageFactory $resultPageFactory,
    MagentoFrameworkJsonHelperData $jsonHelper,
    MagentoFrameworkPricingHelperData $currency,
    ConfproductsWeekpricesimpleprodLoggerLogger $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 MagentoFrameworkControllerResultInterface
    */
    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 (MagentoFrameworkExceptionLocalizedException $e)
    return $this->jsonResponse($e->getMessage());
    catch (Exception $e)
    $this->logger->critical($e);
    return $this->jsonResponse($e->getMessage());



    /**
    * Create json response
    *
    * @return MagentoFrameworkControllerResultInterface
    */
    public function jsonResponse($response = '')

    return $this->getResponse()->representJson(
    $this->jsonHelper->jsonEncode($response)
    );






    share|improve this answer

























    • Thanks for the answer +1 for the efforts :)

      – Aditya Shah
      Aug 13 at 14:47













    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f268492%2fhow-to-get-simple-product-id-from-selected-configurable-attribute-id-and-its-va%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2















    Magento provides function for that, by passing attributes in array format you can get simple product of those variants.




    /magento/module-configurable-product/Model/Product/Type/Configurable.php




    • 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]

    Retrieve used product by attribute values



    public function __construct(
    MagentoConfigurableProductModelProductTypeConfigurable $configurableProTypeModel,
    MagentoCatalogModelProduct $product
    )
    $this->_configurableProTypeModel = $configurableProTypeModel;
    $this->_product = $product;


    $product = $this->productRepository->getById($product_id);
    // Valid format for attributes
    //$attributesInfo = array( $attributeId => $attributeValue);
    $attributesInfo = array( 280 => 145,757=>181);

    $associateProduct = $this->_configurableProTypeModel->getProductByAttributes($attributesInfo, $product);





    share|improve this answer





























      2















      Magento provides function for that, by passing attributes in array format you can get simple product of those variants.




      /magento/module-configurable-product/Model/Product/Type/Configurable.php




      • 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]

      Retrieve used product by attribute values



      public function __construct(
      MagentoConfigurableProductModelProductTypeConfigurable $configurableProTypeModel,
      MagentoCatalogModelProduct $product
      )
      $this->_configurableProTypeModel = $configurableProTypeModel;
      $this->_product = $product;


      $product = $this->productRepository->getById($product_id);
      // Valid format for attributes
      //$attributesInfo = array( $attributeId => $attributeValue);
      $attributesInfo = array( 280 => 145,757=>181);

      $associateProduct = $this->_configurableProTypeModel->getProductByAttributes($attributesInfo, $product);





      share|improve this answer



























        2














        2










        2









        Magento provides function for that, by passing attributes in array format you can get simple product of those variants.




        /magento/module-configurable-product/Model/Product/Type/Configurable.php




        • 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]

        Retrieve used product by attribute values



        public function __construct(
        MagentoConfigurableProductModelProductTypeConfigurable $configurableProTypeModel,
        MagentoCatalogModelProduct $product
        )
        $this->_configurableProTypeModel = $configurableProTypeModel;
        $this->_product = $product;


        $product = $this->productRepository->getById($product_id);
        // Valid format for attributes
        //$attributesInfo = array( $attributeId => $attributeValue);
        $attributesInfo = array( 280 => 145,757=>181);

        $associateProduct = $this->_configurableProTypeModel->getProductByAttributes($attributesInfo, $product);





        share|improve this answer













        Magento provides function for that, by passing attributes in array format you can get simple product of those variants.




        /magento/module-configurable-product/Model/Product/Type/Configurable.php




        • 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]

        Retrieve used product by attribute values



        public function __construct(
        MagentoConfigurableProductModelProductTypeConfigurable $configurableProTypeModel,
        MagentoCatalogModelProduct $product
        )
        $this->_configurableProTypeModel = $configurableProTypeModel;
        $this->_product = $product;


        $product = $this->productRepository->getById($product_id);
        // Valid format for attributes
        //$attributesInfo = array( $attributeId => $attributeValue);
        $attributesInfo = array( 280 => 145,757=>181);

        $associateProduct = $this->_configurableProTypeModel->getProductByAttributes($attributesInfo, $product);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 4 at 5:40









        Aditya ShahAditya Shah

        5,1472 gold badges12 silver badges45 bronze badges




        5,1472 gold badges12 silver badges45 bronze badges


























            1















            You can use this below code to get simple product id based on configurable product ID.



            If you get value of selected configurable product id in js file, then you can pass value using ajax and call controller to get simple product id.
            If you want to get simple product id by compare value of selected attribute value, then you can use commented code also.



            Add this below code in your controller :



            <?php
            namespace RHBlogControllerIndex;

            class Test extends MagentoFrameworkAppActionAction

            /**
            * @var MagentoCatalogApiProductRepositoryInterface
            */
            protected $productRepository;

            /**
            * @var MagentoStoreModelStoreManagerInterface
            */
            protected $storeManager;
            /**
            * [__construct description]
            * @param MagentoCatalogApiProductRepositoryInterface $productRepository [description]
            * @param MagentoStoreModelStoreManagerInterface $storeManager [description]
            */
            public function __construct(
            ....
            MagentoCatalogApiProductRepositoryInterface $productRepository,
            MagentoStoreModelStoreManagerInterface $storeManager
            ....
            )
            ....
            $this->productRepository = $productRepository;
            $this->storeManager = $storeManager;
            ....


            public function execute()
            $configurable_id = '2671';
            $product = $this->productRepository->getById($configurable_id);
            $storeId = $this->storeManager->getStore()->getId();
            $productTypeInstance = $product->getTypeInstance();
            $productTypeInstance->setStoreFilter($storeId, $product);
            $usedProducts = $productTypeInstance->getUsedProducts($product);

            foreach ($usedProducts as $child)
            echo "Simple Product ID : ".$child->getId() . "<br/>";
            // $selected_option_val = $child->getAttributeText('color');
            // if ($selected_option_val == 'your_selected_attr_val')
            // return $child->getId();
            //








            share|improve this answer

























            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Apr 4 at 5:49















            1















            You can use this below code to get simple product id based on configurable product ID.



            If you get value of selected configurable product id in js file, then you can pass value using ajax and call controller to get simple product id.
            If you want to get simple product id by compare value of selected attribute value, then you can use commented code also.



            Add this below code in your controller :



            <?php
            namespace RHBlogControllerIndex;

            class Test extends MagentoFrameworkAppActionAction

            /**
            * @var MagentoCatalogApiProductRepositoryInterface
            */
            protected $productRepository;

            /**
            * @var MagentoStoreModelStoreManagerInterface
            */
            protected $storeManager;
            /**
            * [__construct description]
            * @param MagentoCatalogApiProductRepositoryInterface $productRepository [description]
            * @param MagentoStoreModelStoreManagerInterface $storeManager [description]
            */
            public function __construct(
            ....
            MagentoCatalogApiProductRepositoryInterface $productRepository,
            MagentoStoreModelStoreManagerInterface $storeManager
            ....
            )
            ....
            $this->productRepository = $productRepository;
            $this->storeManager = $storeManager;
            ....


            public function execute()
            $configurable_id = '2671';
            $product = $this->productRepository->getById($configurable_id);
            $storeId = $this->storeManager->getStore()->getId();
            $productTypeInstance = $product->getTypeInstance();
            $productTypeInstance->setStoreFilter($storeId, $product);
            $usedProducts = $productTypeInstance->getUsedProducts($product);

            foreach ($usedProducts as $child)
            echo "Simple Product ID : ".$child->getId() . "<br/>";
            // $selected_option_val = $child->getAttributeText('color');
            // if ($selected_option_val == 'your_selected_attr_val')
            // return $child->getId();
            //








            share|improve this answer

























            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Apr 4 at 5:49













            1














            1










            1









            You can use this below code to get simple product id based on configurable product ID.



            If you get value of selected configurable product id in js file, then you can pass value using ajax and call controller to get simple product id.
            If you want to get simple product id by compare value of selected attribute value, then you can use commented code also.



            Add this below code in your controller :



            <?php
            namespace RHBlogControllerIndex;

            class Test extends MagentoFrameworkAppActionAction

            /**
            * @var MagentoCatalogApiProductRepositoryInterface
            */
            protected $productRepository;

            /**
            * @var MagentoStoreModelStoreManagerInterface
            */
            protected $storeManager;
            /**
            * [__construct description]
            * @param MagentoCatalogApiProductRepositoryInterface $productRepository [description]
            * @param MagentoStoreModelStoreManagerInterface $storeManager [description]
            */
            public function __construct(
            ....
            MagentoCatalogApiProductRepositoryInterface $productRepository,
            MagentoStoreModelStoreManagerInterface $storeManager
            ....
            )
            ....
            $this->productRepository = $productRepository;
            $this->storeManager = $storeManager;
            ....


            public function execute()
            $configurable_id = '2671';
            $product = $this->productRepository->getById($configurable_id);
            $storeId = $this->storeManager->getStore()->getId();
            $productTypeInstance = $product->getTypeInstance();
            $productTypeInstance->setStoreFilter($storeId, $product);
            $usedProducts = $productTypeInstance->getUsedProducts($product);

            foreach ($usedProducts as $child)
            echo "Simple Product ID : ".$child->getId() . "<br/>";
            // $selected_option_val = $child->getAttributeText('color');
            // if ($selected_option_val == 'your_selected_attr_val')
            // return $child->getId();
            //








            share|improve this answer













            You can use this below code to get simple product id based on configurable product ID.



            If you get value of selected configurable product id in js file, then you can pass value using ajax and call controller to get simple product id.
            If you want to get simple product id by compare value of selected attribute value, then you can use commented code also.



            Add this below code in your controller :



            <?php
            namespace RHBlogControllerIndex;

            class Test extends MagentoFrameworkAppActionAction

            /**
            * @var MagentoCatalogApiProductRepositoryInterface
            */
            protected $productRepository;

            /**
            * @var MagentoStoreModelStoreManagerInterface
            */
            protected $storeManager;
            /**
            * [__construct description]
            * @param MagentoCatalogApiProductRepositoryInterface $productRepository [description]
            * @param MagentoStoreModelStoreManagerInterface $storeManager [description]
            */
            public function __construct(
            ....
            MagentoCatalogApiProductRepositoryInterface $productRepository,
            MagentoStoreModelStoreManagerInterface $storeManager
            ....
            )
            ....
            $this->productRepository = $productRepository;
            $this->storeManager = $storeManager;
            ....


            public function execute()
            $configurable_id = '2671';
            $product = $this->productRepository->getById($configurable_id);
            $storeId = $this->storeManager->getStore()->getId();
            $productTypeInstance = $product->getTypeInstance();
            $productTypeInstance->setStoreFilter($storeId, $product);
            $usedProducts = $productTypeInstance->getUsedProducts($product);

            foreach ($usedProducts as $child)
            echo "Simple Product ID : ".$child->getId() . "<br/>";
            // $selected_option_val = $child->getAttributeText('color');
            // if ($selected_option_val == 'your_selected_attr_val')
            // return $child->getId();
            //









            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 3 at 9:21









            Rohan HapaniRohan Hapani

            8,8984 gold badges21 silver badges66 bronze badges




            8,8984 gold badges21 silver badges66 bronze badges















            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Apr 4 at 5:49

















            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Apr 4 at 5:49
















            Thanks for the answer +1 for the efforts :)

            – Aditya Shah
            Apr 4 at 5:49





            Thanks for the answer +1 for the efforts :)

            – Aditya Shah
            Apr 4 at 5:49











            1















            Try this.



            public function __construct(
            MagentoStoreModelStoreManagerInterface $storeManager,
            MagentoCatalogModelResourceModelEavAttribute $eavAttribute,
            MagentoCatalogModelProductRepository $productRepository
            )
            $this->storeManager = $storeManager;
            $this->eavAttribute = $eavAttribute;
            $this->productRepository = $productRepository;


            public function getSimpleProductId()

            $simple_product_id = null;
            $configurable_product_id = 2671;
            $color_id = 280;
            $size_id = 757;

            $color_value = 142;
            $size_value = 181;

            $color_code = $this->eavAttribute->load($color_id)->getAttributeCode();
            $size_code = $this->eavAttribute->load($size_id)->getAttributeCode();

            $product = $this->getProductById($configurable_product_id);
            $productTypeInstance = $product->getTypeInstance();
            $simple_products = $productTypeInstance->getUsedProducts($product);
            foreach ($simple_products as $simple)

            if($simple->getData($color_code) == $color_value && $simple->getData($size_code) == $size_value)

            $simple_product_id = $simple->getId();



            return $simple_product_id;


            public function getProductById($id)

            return $this->productRepository->getById($id, false, $this->storeManager->getStore()->getId());






            share|improve this answer

























            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Apr 4 at 5:49















            1















            Try this.



            public function __construct(
            MagentoStoreModelStoreManagerInterface $storeManager,
            MagentoCatalogModelResourceModelEavAttribute $eavAttribute,
            MagentoCatalogModelProductRepository $productRepository
            )
            $this->storeManager = $storeManager;
            $this->eavAttribute = $eavAttribute;
            $this->productRepository = $productRepository;


            public function getSimpleProductId()

            $simple_product_id = null;
            $configurable_product_id = 2671;
            $color_id = 280;
            $size_id = 757;

            $color_value = 142;
            $size_value = 181;

            $color_code = $this->eavAttribute->load($color_id)->getAttributeCode();
            $size_code = $this->eavAttribute->load($size_id)->getAttributeCode();

            $product = $this->getProductById($configurable_product_id);
            $productTypeInstance = $product->getTypeInstance();
            $simple_products = $productTypeInstance->getUsedProducts($product);
            foreach ($simple_products as $simple)

            if($simple->getData($color_code) == $color_value && $simple->getData($size_code) == $size_value)

            $simple_product_id = $simple->getId();



            return $simple_product_id;


            public function getProductById($id)

            return $this->productRepository->getById($id, false, $this->storeManager->getStore()->getId());






            share|improve this answer

























            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Apr 4 at 5:49













            1














            1










            1









            Try this.



            public function __construct(
            MagentoStoreModelStoreManagerInterface $storeManager,
            MagentoCatalogModelResourceModelEavAttribute $eavAttribute,
            MagentoCatalogModelProductRepository $productRepository
            )
            $this->storeManager = $storeManager;
            $this->eavAttribute = $eavAttribute;
            $this->productRepository = $productRepository;


            public function getSimpleProductId()

            $simple_product_id = null;
            $configurable_product_id = 2671;
            $color_id = 280;
            $size_id = 757;

            $color_value = 142;
            $size_value = 181;

            $color_code = $this->eavAttribute->load($color_id)->getAttributeCode();
            $size_code = $this->eavAttribute->load($size_id)->getAttributeCode();

            $product = $this->getProductById($configurable_product_id);
            $productTypeInstance = $product->getTypeInstance();
            $simple_products = $productTypeInstance->getUsedProducts($product);
            foreach ($simple_products as $simple)

            if($simple->getData($color_code) == $color_value && $simple->getData($size_code) == $size_value)

            $simple_product_id = $simple->getId();



            return $simple_product_id;


            public function getProductById($id)

            return $this->productRepository->getById($id, false, $this->storeManager->getStore()->getId());






            share|improve this answer













            Try this.



            public function __construct(
            MagentoStoreModelStoreManagerInterface $storeManager,
            MagentoCatalogModelResourceModelEavAttribute $eavAttribute,
            MagentoCatalogModelProductRepository $productRepository
            )
            $this->storeManager = $storeManager;
            $this->eavAttribute = $eavAttribute;
            $this->productRepository = $productRepository;


            public function getSimpleProductId()

            $simple_product_id = null;
            $configurable_product_id = 2671;
            $color_id = 280;
            $size_id = 757;

            $color_value = 142;
            $size_value = 181;

            $color_code = $this->eavAttribute->load($color_id)->getAttributeCode();
            $size_code = $this->eavAttribute->load($size_id)->getAttributeCode();

            $product = $this->getProductById($configurable_product_id);
            $productTypeInstance = $product->getTypeInstance();
            $simple_products = $productTypeInstance->getUsedProducts($product);
            foreach ($simple_products as $simple)

            if($simple->getData($color_code) == $color_value && $simple->getData($size_code) == $size_value)

            $simple_product_id = $simple->getId();



            return $simple_product_id;


            public function getProductById($id)

            return $this->productRepository->getById($id, false, $this->storeManager->getStore()->getId());







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 3 at 9:36









            Yash ShahYash Shah

            1,2282 silver badges12 bronze badges




            1,2282 silver badges12 bronze badges















            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Apr 4 at 5:49

















            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Apr 4 at 5:49
















            Thanks for the answer +1 for the efforts :)

            – Aditya Shah
            Apr 4 at 5:49





            Thanks for the answer +1 for the efforts :)

            – Aditya Shah
            Apr 4 at 5:49











            1















            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 MagentoFrameworkAppActionAction



            protected $resultPageFactory;
            protected $jsonHelper;
            protected $productObj;
            protected $configurableProTypeModel;
            protected $logger;
            protected $currency;
            /**
            * Constructor
            *
            * @param MagentoFrameworkAppActionContext $context
            * @param MagentoFrameworkJsonHelperData $jsonHelper
            */
            public function __construct(
            MagentoFrameworkAppActionContext $context,
            MagentoConfigurableProductModelProductTypeConfigurable $configurableProTypeModel,
            MagentoCatalogModelProductRepository $productRepository,
            MagentoFrameworkViewResultPageFactory $resultPageFactory,
            MagentoFrameworkJsonHelperData $jsonHelper,
            MagentoFrameworkPricingHelperData $currency,
            ConfproductsWeekpricesimpleprodLoggerLogger $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 MagentoFrameworkControllerResultInterface
            */
            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 (MagentoFrameworkExceptionLocalizedException $e)
            return $this->jsonResponse($e->getMessage());
            catch (Exception $e)
            $this->logger->critical($e);
            return $this->jsonResponse($e->getMessage());



            /**
            * Create json response
            *
            * @return MagentoFrameworkControllerResultInterface
            */
            public function jsonResponse($response = '')

            return $this->getResponse()->representJson(
            $this->jsonHelper->jsonEncode($response)
            );






            share|improve this answer

























            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Aug 13 at 14:47















            1















            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 MagentoFrameworkAppActionAction



            protected $resultPageFactory;
            protected $jsonHelper;
            protected $productObj;
            protected $configurableProTypeModel;
            protected $logger;
            protected $currency;
            /**
            * Constructor
            *
            * @param MagentoFrameworkAppActionContext $context
            * @param MagentoFrameworkJsonHelperData $jsonHelper
            */
            public function __construct(
            MagentoFrameworkAppActionContext $context,
            MagentoConfigurableProductModelProductTypeConfigurable $configurableProTypeModel,
            MagentoCatalogModelProductRepository $productRepository,
            MagentoFrameworkViewResultPageFactory $resultPageFactory,
            MagentoFrameworkJsonHelperData $jsonHelper,
            MagentoFrameworkPricingHelperData $currency,
            ConfproductsWeekpricesimpleprodLoggerLogger $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 MagentoFrameworkControllerResultInterface
            */
            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 (MagentoFrameworkExceptionLocalizedException $e)
            return $this->jsonResponse($e->getMessage());
            catch (Exception $e)
            $this->logger->critical($e);
            return $this->jsonResponse($e->getMessage());



            /**
            * Create json response
            *
            * @return MagentoFrameworkControllerResultInterface
            */
            public function jsonResponse($response = '')

            return $this->getResponse()->representJson(
            $this->jsonHelper->jsonEncode($response)
            );






            share|improve this answer

























            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Aug 13 at 14:47













            1














            1










            1









            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 MagentoFrameworkAppActionAction



            protected $resultPageFactory;
            protected $jsonHelper;
            protected $productObj;
            protected $configurableProTypeModel;
            protected $logger;
            protected $currency;
            /**
            * Constructor
            *
            * @param MagentoFrameworkAppActionContext $context
            * @param MagentoFrameworkJsonHelperData $jsonHelper
            */
            public function __construct(
            MagentoFrameworkAppActionContext $context,
            MagentoConfigurableProductModelProductTypeConfigurable $configurableProTypeModel,
            MagentoCatalogModelProductRepository $productRepository,
            MagentoFrameworkViewResultPageFactory $resultPageFactory,
            MagentoFrameworkJsonHelperData $jsonHelper,
            MagentoFrameworkPricingHelperData $currency,
            ConfproductsWeekpricesimpleprodLoggerLogger $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 MagentoFrameworkControllerResultInterface
            */
            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 (MagentoFrameworkExceptionLocalizedException $e)
            return $this->jsonResponse($e->getMessage());
            catch (Exception $e)
            $this->logger->critical($e);
            return $this->jsonResponse($e->getMessage());



            /**
            * Create json response
            *
            * @return MagentoFrameworkControllerResultInterface
            */
            public function jsonResponse($response = '')

            return $this->getResponse()->representJson(
            $this->jsonHelper->jsonEncode($response)
            );






            share|improve this 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 MagentoFrameworkAppActionAction



            protected $resultPageFactory;
            protected $jsonHelper;
            protected $productObj;
            protected $configurableProTypeModel;
            protected $logger;
            protected $currency;
            /**
            * Constructor
            *
            * @param MagentoFrameworkAppActionContext $context
            * @param MagentoFrameworkJsonHelperData $jsonHelper
            */
            public function __construct(
            MagentoFrameworkAppActionContext $context,
            MagentoConfigurableProductModelProductTypeConfigurable $configurableProTypeModel,
            MagentoCatalogModelProductRepository $productRepository,
            MagentoFrameworkViewResultPageFactory $resultPageFactory,
            MagentoFrameworkJsonHelperData $jsonHelper,
            MagentoFrameworkPricingHelperData $currency,
            ConfproductsWeekpricesimpleprodLoggerLogger $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 MagentoFrameworkControllerResultInterface
            */
            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 (MagentoFrameworkExceptionLocalizedException $e)
            return $this->jsonResponse($e->getMessage());
            catch (Exception $e)
            $this->logger->critical($e);
            return $this->jsonResponse($e->getMessage());



            /**
            * Create json response
            *
            * @return MagentoFrameworkControllerResultInterface
            */
            public function jsonResponse($response = '')

            return $this->getResponse()->representJson(
            $this->jsonHelper->jsonEncode($response)
            );







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 13 at 14:41









            Liz Eipe CLiz Eipe C

            7175 silver badges8 bronze badges




            7175 silver badges8 bronze badges















            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Aug 13 at 14:47

















            • Thanks for the answer +1 for the efforts :)

              – Aditya Shah
              Aug 13 at 14:47
















            Thanks for the answer +1 for the efforts :)

            – Aditya Shah
            Aug 13 at 14:47





            Thanks for the answer +1 for the efforts :)

            – Aditya Shah
            Aug 13 at 14:47

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f268492%2fhow-to-get-simple-product-id-from-selected-configurable-attribute-id-and-its-va%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Grendel Contents Story Scholarship Depictions Notes References Navigation menu10.1093/notesj/gjn112Berserkeree

            Area configuration aggregation error after install Porto themeMagento 2.1 CE Installed but front/backend not loading/workingCSS not loading on page within Magento 2 pageCannot install module in Magento 2no commands defined in the “setup” namespace. in Magento2Magento 2: Static files are present but shows 404Why do i have to always run the commands to clean cache in Magento 2.1.8?Failure reason: 'Unable to unserialize value.'Error 500 after magento migrationIn production mode the site does not loadMagento 2 : Error 500 after installing

            Middle Expansion Olielle Resaix Definition: Uttering songs of triumph shouting with joy triumphant exulting Sejunction Journal 붙다 달 고급 품목 외출 The stretch trades the screeching tin. Definition: The act of speaking with a drawl a drawl Cough Sand Definition: An uproar a quarrel a noisy outbreak Shake Iron Publicize Horse House Baby 사과 Resaix Flaggy Jelly Temporary Unequaled Puppet A drop in the bucket Shrew 성격 회원 성질 미팅 The burn frames the tacky quality. Materialistic The smoke reduces the way. Yammoe Nondescript Cheek 얼굴 배 약하다 날리다 타다 The illegal country shows the iron. Help Rule Drearien Smoke Teaching Meaty Wasp Abraham Lincoln Jaws 진심 수리하다 Size Cork Idea Convert Think Lark John Lennon 거울 청소 군 추천하다 아이스크림