Magento – Magento 2: Get total no. of colors available of Configurable Product

configurable-productmagento-2.1.7

I have configurable product which is combination of color and size. I have to get total no. of colors for the configurable product on the listing page.

I am able to get all the child products but not getting exact total of available colors.

There are 15 colors and 3 sizes so total child products is 45. I have to get total no. of colors.

Please give me some solution.

Best Answer

You can use help of class Magento\ConfigurableProduct\Model\Product\Type\Configurable refer here

Try like this

private $productRepository; 
...
public function __construct(
    ...
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ...
) {
    ...
    $this->productRepository = $productRepository;
    ...
}

public function execute()
{
    $product = $this->productRepository->getById(83); //Configurable Product Id

    $colorAttributeId = $product->getResource()->getAttribute('color')->getId(); // Get Color Attribute Id
    $configurableAttrs = $product->getTypeInstance()->getConfigurableAttributesAsArray($product); // Get Used Attributes with its values

    if(isset($configurableAttrs[$colorAttributeId])){
        echo count($configurableAttrs[$colorAttributeId]['values']); // Gives you the count
        echo "<pre>";print_r($configurableAttrs[$colorAttributeId]['values']); // Give you values used
    }
}