3

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?

2 Answers 2

2

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}
0
1

In this case,you need to rewrite class Magento\ConfigurableProduct\Helper\Data;

then at getOptions() function at

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');

$options['qty'][$productId]=$StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId()); 

after $images = $this->getGalleryImages($product);

2

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.