1

If I have a configurable product and I select color red, then how can I get the id of that virtual product that has been selected?

I would need to do this each time when a new color is selected on the product page to get the id of the new selected virtual product.

Thanks!

1 Answer 1

3

Offering the solution that I have come to not sure if its the best way to do it but works none the less.

When the product option is clicked call an ajax function with the id of the product and the option id that is currently selected.

var id = <?php echo $_product->getId() ?>;
var option_id = $('.swatch-option.selected').attr('option-id');


$.ajax({
    url: "module_route/index/class_name",
    data: { id : id, option_id : option_id},
    type: "POST",
    success: function(result){
        console.log(result);
    }
}); 

In your module controller

namespace Module\Name\Controller\Index;
class StockLevel extends \Magento\Framework\App\Action\Action
{

    public function execute()
    {
        // Get info sent from ajax
        $id = $_POST['id'];
        $option_id = $_POST['option_id'];
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->get('Magento\Catalog\Model\Product')->load($id);
        $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');

        $productTypeInstance = $product->getTypeInstance();
        $usedProducts = $productTypeInstance->getUsedProducts($product);

        foreach ($usedProducts  as $child) {

            // get all the child info
            echo "<pre>";
            print_r($child->getData());
            echo "<pre>";

            $child_option = $child->getData('option you are comparing color ect');
            if ($child_option == $option_id) {
                $stock = $StockState->getStockQty($child->getId(), $child->getStore()->getWebsiteId());
                echo $stock;
            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.