0

I'm looking for a way to grab the values of an attribute (let's say color) from all simple products associated with a configurable.

So if my associated simple products are:

  • Simple1 - Red
  • Simple2 - Blue
  • Simple3 - Green

On my configurable, I'm looking for a way to output "Red, Blue, Green".

Any suggestions would be appreciated.

1 Answer 1

0

Disclaimer: Use of ObjectManager Directly is highly discouraged in a production environment. Inject the dependencies in the respective class instead.

<?php 
// custom script to get associated simple products with their options for a configurable product     
ini_set('display_errros',1);
ini_set('memory_limit',-1);
error_reporting(E_ALL);

require __DIR__ . '/app/bootstrap.php';

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

$ObjectManager = $bootstrap->getObjectManager();

$state = $ObjectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');

$configurableParentSku = 'MH07';      

$_productResourceModel = $ObjectManager->create('\Magento\Catalog\Model\ResourceModel\Product'); 
$productId = $_productResourceModel->getIdBySku($configurableParentSku);

echo 'Configurable Product Parent Id: ' . $productId . PHP_EOL; 

$_productModel = $ObjectManager->create('\Magento\Catalog\Model\ProductRepository'); 
$_product = $_productModel->get($configurableParentSku);

echo 'Name: ' . $_product->getName() . PHP_EOL; 

// returns associated simple product
$assocSimpleProducts = $_product->getTypeInstance()->getUsedProducts($_product);

foreach ($assocSimpleProducts as $_assocSimpleProduct) {
    echo 'Sku: ' . $_assocSimpleProduct->getSku() . PHP_EOL; 
}

// returns associated simple product options

$assocSimpleProductsOptions = $_product->getTypeInstance()->getConfigurableOptions($_product);

echo '$assocSimpleProductsOptions: ' . print_r($assocSimpleProductsOptions,true) . PHP_EOL; 

// returns used options and values of a given configurable product
$productAttributeOptions = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);

echo '$productAttributeOptions: ' . print_r($productAttributeOptions,true) . PHP_EOL; 

$attributeOptions = array();
foreach ($productAttributeOptions as $productAttribute) {
    foreach ($productAttribute['values'] as $attribute) {
        $attributeOptions[$productAttribute['label']][$attribute['value_index']] = $attribute['store_label'];
    }
}

echo '$attributeOptions: ' . print_r($attributeOptions,true) . PHP_EOL; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.