5 Programming Questions and Answers Regarding Magento Sort Products – Part 1

February 15, 2017,
5 Programming Questions and Answers Regarding Magento Sort Products – Part 1
Sorting products in an online store is a simple but one of the most effective ways which enable your customers to find the best products on your store in a blink. As it is an important functionality for online stores, hence you will find various automatic tools i.e. plugins for implementing this on your e-store. For example, if your website is based on Magento you can use Magento sort products extension. Similarly, you can find plugins and extensions for all other shopping carts. However, there are plenty of developers who want to use custom programming for implementing product sorting. Keeping this approach of end users in mind, FMEAddons has picked up this week’s hot questions and answers give by the top community developers.

Question No. 1

How to sort products by newest in Magento? Is there any changes required in catalog.xml or can I use a third party extension for this?

Answer:

 
Methods 1
You can perform this action by simply using the code is given below (Custom coding)
$_newest_productCollection = Mage::getResourceModel('reports/product_collection')
  ->addAttributeToSelect('*')
  ->addAttributeToFilter('visibility', $visibility)
  ->setOrder('created_at', 'desc')
$_newest_productCollection->load();
Method 2
If you are not able to code, just download Magento sort products extension. It will help you to resolve product sorting in various ways i.e. sort by price, sort by name, sort by popularity, newest etc.

Question No. 2

How to sort products by quantity and price descending? The user wants to sort category which has maximum quantity (products). Means if a category has maximum products then it should come first and then lower quantity products should be listed. This is done by writing the below code in Collection.php
public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC)
{
    if ($attribute == 'position') {
   /**** Sorting for quantity starts***************/         
        //join the stock status index table for the current website and check if the product is saleable and the qtu.
        $select = $this->getSelect();
        $select->joinLeft(
            array('stock_qty' => $this->getTable('cataloginventory/stock_status')),
            'e.entity_id = stock_qty.product_id AND stock_qty.website_id='.Mage::app()->getWebsite()->getId(),
            array(
                'salable' => 'stock_qty.stock_status',
                'qty' => 'stock_qty.qty'
            )
        );
        //get the reversed sorting
        //if by position ascending, then you need to sort by qty descending and the other way around
        $reverseDir = ($dir == 'ASC') ? 'DESC' : 'ASC';
        //this is optional - it shows the in stock products above the out of stock ones independent if sorting by position ascending or descending
        $this->getSelect()->order('salable DESC');
        //sort by qty
        $this->getSelect()->order('qty '.$reverseDir);
        return $this;      

/**** Sorting for quantity ends ***************/  

    } elseif($attribute == 'is_saleable'){
        $this->getSelect()->order("is_saleable " . $dir);
        return $this;
    }

    $storeId = $this->getStoreId();
    if ($attribute == 'price' && $storeId != 0) {
        $this->addPriceData();
        $this->getSelect()->order("price_index.min_price {$dir}");

        return $this;
    }

    if ($this->isEnabledFlat()) {
        $column = $this->getEntity()->getAttributeSortColumn($attribute);

        if ($column) {
            $this->getSelect()->order("e.{$column} {$dir}");
        }
        else if (isset($this->_joinFields[$attribute])) {
            $this->getSelect()->order($this->_getAttributeFieldName($attribute) . ' ' . $dir);
        }

        return $this;
    } else {
        $attrInstance = $this->getEntity()->getAttribute($attribute);
        if ($attrInstance && $attrInstance->usesSource()) {
            $attrInstance->getSource()
                ->addValueSortToCollection($this, $dir);
            return $this;
        }
    }

    return parent::addAttributeToSort($attribute, $dir);
}
The user also wants to sort products just like category (products quantity and price both in descending). For example
Product  Quantity Price
-------  -------- -------
  A         100   9000
  B         100   8000
  C         89    7000
  D         80    6000 
The user tried this by going to System> Configuration> Catalog> Product Listing Sort by = Price, but it does not work for him.

Answer:

You just need to add after sorting quantity by descending order
 $this->getSelect()->order('price DESC');
Here is the complete code
$select = $this->getSelect();
        $select->joinLeft(
            array('stock_qty' => $this->getTable('cataloginventory/stock_status')),
            'e.entity_id = stock_qty.product_id AND stock_qty.website_id='.Mage::app()->getWebsite()->getId(),
            array(
                'salable' => 'stock_qty.stock_status',
                'qty' => 'stock_qty.qty'
            )
        );
        //get the reversed sorting
        //if by position ascending, then you need to sort by qty descending and the other way around
        $reverseDir = ($dir == 'ASC') ? 'DESC' : 'ASC';
        //this is optional - it shows the in stock products above the out of stock ones independent if sorting by position ascending or descending
        $this->getSelect()->order('salable DESC');

        //sort by qty
        $this->getSelect()->order('qty '.$reverseDir);
        $this->getSelect()->order('price DESC');
        return $this;

Question No. 3

How to sort products list by product type in Magento? User is looking for the solution of sorting product list by type in Magento, means grouped product first and after those simple products

Answer:

To create a new collection just use addAttributeToSort(). And if you want to display existing collections with preceding order, use the unshiftOrder() function.

Question No. 4

The user has multiple products in the store based on Magento that needs t be sorted in new categories based on different attributes. For example, if a product has attribute "Size" with a value of "Large" then product should be in Category 2 and so on. Is there any solution to perform this with the help of code?

Answer:

For this, you can use the setCategoryIds function. Try the code given below
$product->load($productId);
if( strcmp($product->getAttributeText('COLOR') , 'Blue') == 0 ){
    $product->setCategoryIds(array('cat1Id' ,'cat2Id'));
}
$product->save();

Question No. 5

The user wants to filter the product collection. For this, he overridden the Mage_Catalog_Block_Product_List and have the following piece of code.
$collection = parent::_getProductCollection();
$collection->addAttributeToFilter('language', array('in' => 
array('B','C','E')));
$collection->addAttributeToSort('language', 'DESC');

return $this->_productCollection; 
On the front end, products are currently sorted in "E, C, B" form. If attribute set to "ASC", product sorting changed to "B, C, E". The user wants to show products in the order "E, B, C". How to do this? The user has also tried the code:
 $collection = parent::_getProductCollection();
 $collection->addAttributeToFilter('language', 
 array('finset'=>'E','C,E,B'));

return $this->_productCollection;
But it only shows products set as "E"

Answer:

To resolve your issue you can try:
parent::_getProductCollection()
        ->addAttributeToFilter('language', array('finset'=>'B,C,E'));

return $this->_productCollection;

Download Magento Sort Products Extension

magento soft products