How to sort associated products in a grouped product

All we need is an easy explanation of the problem, so here it is.

I have an issue which I’m not able to find a solution here and is how to sort all the associated products of a grouped product automatically for every grouped product in the store?

I have 1850 grouped products with their associates but I want to sort these associated products by price from the cheapest to the most expensive. (Up to down)

Anyone know how to do this?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

There are two ways to achieve this.

  1. Rewrite the method responsible for creating grouped product association. This saves the positioning in the DB.

For #1, you will need to look at Mage_Catalog_Model_Resource_Product_Link::saveProductLinks. Essentially, in the foreach ($attributes as $attributeInfo) loop of this method, one of the iterations will be for the catalog_product_link_attribute_int table, which hold the positions under the column value when product_link_attribute_id = 2.

You’ll need to somehow retrieve the product prices and use that as the sorting index. I recommend pre-loading them into an easily accessible array, so that all you need to do is load it once and access it during the entire save.

  1. Sort on-the-fly when the products get rendered on the frontend. This does not save the positions.

This is easier but slower and only superficial. You’ll just need to find the block responsible for rendering the group products and sort the collection or array of products.

I recommend #1 and it’s pretty straightforward once you understand the method saveProductLinks.

Method 2

I finally found something different that in my case works too and it’s easier but maybe could work temporally while you are finding a better method.

You need to check this file:

/var/www/magento/app/code/core/Mage/Catalog/Model/Product/Type/Grouped.php

And find the function

getAssociatedProducts($product = null) {}

Then only you need to add a ->setOrder('price', 'ASC') in $collection variable.

Looks like this:

 $collection = $this->getAssociatedProductCollection($product)
                ->addAttributeToSelect('*')
                ->addFilterByRequiredOptions()
                ->setOrder('price','ASC')
                ->addStoreFilter($this->getStoreFilter($product))
                ->addAttributeToFilter('status', array('in' => $this->getStatusFilters($product)));

Flush caches and check the grouped products.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply