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}