2

How can I get all the available colors of a single product in Magento 2?

2
  • Is this simple product a configurable product or simple product? color is a dropdown attribute or multi-select attribute?
    – Amit Bera
    Aug 13, 2018 at 11:32
  • It is a configurable product
    – glafche
    Aug 13, 2018 at 11:44

1 Answer 1

2

Assume that you have configurable product object:

Then first you have to get it all child products ids using

$childrenIds = $configurableProduct->getTypeInstance()->getChildrenIds($configurableProduct->getId());

Then create a product collection and filter that collection by$childrenIds

$productCollectionFactory->create()->addIdFilter($childrenIds);
 //Assume that your color attribute code is 'color'
$productCollectionFactory->addAttributeToSelect('color');
// optimized the collection
$productCollectionFactory->setPageSize(count($childrenIds))->setCurPage(1);   
$productCollectionFactory->groupByAttribute('color');

foreach($productCollectionFactory as $product){
    echo  $product->getData('color');
}

Here $productCollectionFactory is object of \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory

It's working fine.

1
  • Use setPageSize and setCurPage need to use for optimized the collection
    – Amit Bera
    Aug 14, 2018 at 14:21

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.