Magento 2 – How to Access Configurable Product Stock Qty via JS

configurable-productmagento2

Someone knows how to get qty for each simple product of configurable product via javascript in product page?

It seems that spConfig retrieved with

#product_addtocart_form": {
    "configurable": {
        "spConfig": <?php /* @escapeNotVerified */ echo $block->getJsonConfig() ?>
    }
}

hasn't data about qty.

I have to retrieve it with custom code or do you have some hints on how to find qty information?

Best Answer

Thx to @Amit Bera for hints, here my answer.

Override \Magento\ConfigurableProduct\Model\ConfigurableAttributeData and extends getAttributeOptionsData() adding qty field:

/**
 * @var \\Magento\CatalogInventory\Api\StockStateInterface
 */
protected $_stockState;



/**
 *
 */
public function __construct(
    \Magento\CatalogInventory\Api\StockStateInterface $stockState
) {

    $this->_stockState = $stockState;

}



/**
 * @param Attribute $attribute
 * @param array $config
 * @return array
 */
protected function getAttributeOptionsData($attribute, $config) {

    $attributeOptionsData = [];
    foreach ($attribute->getOptions() as $attributeOption) {

        $optionId = $attributeOption['value_index'];

        $attributeOptionsData[] = [
            'id' => $optionId,
            'label' => $attributeOption['label'],
            'products' => isset($config[$attribute->getAttributeId()][$optionId])
                ? $config[$attribute->getAttributeId()][$optionId]
                : [],
            'qty' => isset($config[$attribute->getAttributeId()][$optionId][0])
                ? $this->_stockState->getStockQty($config[$attribute->getAttributeId()][$optionId][0])
                : '',
        ];
    }

    return $attributeOptionsData;

}

Now in \app\code\xxx\yyy\view\frontend\templates\product\view\type\options\configurable.phtml you could retrieve simple product qty with simple js:

var config = <?php /* @escapeNotVerified */ echo $block->getJsonConfig() ?>;
.....
// loop options config.attributes[attribute_id].options
// for each simple product to obtain:
// Object {id: "231", label: "M", products: ["2089"], qty: 2}