0

I need to get all the simple products associated with a configurable, but sorted by the super attribute position, for example, size.

If I have $parent_product, I need $child_s, $child_xl, $child_m, $child_xs sorted by: xs -> position 0, s -> positon 1, m -> position 2, xl -> position 3. So the product order should be $child_xs, $child_s, $child_m, $child_xl

I begin getting all the child product of a configurable this way:

$simpleCollection = Mage::getModel('catalog/product_type_configurable')
                                    ->getUsedProducts(null,$_product);

later I iterate a foreach loop where I use only the products with stock:

foreach ($simpleCollection as $simple):
    if($stockItem->getIsInStock()):
        $label = $simple->getResource()->getAttribute('size')->getFrontend()->getValue($simple);
        echo $label;
    endif;
endforeach;

In the example I print the label of the attibute, but I need and use more data of the products.

The simple products remain unsorted.

I tryed:

usort($simpleCollection, function ($item1, $item2) {
    if ($item1['size'] == $item2['size']) return 0;
    return $item1['size'] < $item2['size'] ? -1 : 1;
});

But it is sorting the products by the size value, that sometimes is the same as product position but not always. So the order I get is not correct, I need the same order in the products than the size position.

0

Finally I solved it this way:

$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'size');
if ($attribute->usesSource()) {
    $sorted_options = $attribute->getSource()->getAllOptions(false);
}

foreach ($sorted_options as $one_option):
    foreach ($simpleCollection as $simple):
        $stockItem = $simple->getStockItem();
        if(!$stockItem->getIsInStock()) { continue; }
        $label = $simple->getResource()->getAttribute('size')->getFrontend()->getValue($simple);
        if ($label != $one_option['label']) { continue; }
        echo $label;
    endforeach;
endforeach;

Doesn't seem very optimized to me, but it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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