Back to Top

Display collection records in a specific order except for DESC or ASC sort order

Updated 17 June 2024

Display collection records in a specific order except for DESC or ASC sort order:

In Magento 2, Sometimes you need to display collection results in a specific order except for DESC or ASC sort orders in the query.
Please follow the below steps to do this:

1. Create a module.

2. Create layout xml file (routename_controller_action.xml) inside the app/code/Vendor/Module/view/frontend/layout directory.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="Vendor\Module\Block\Demo\Index" 
            name="blogs_demo_index" 
            template="Vendor_Module::demo.phtml" 
            cacheable= "false"/>
    </referenceContainer>
</page>

3. Create a Block file (Index.php) inside the app/code/Vendor/Module/Block directory. In which, we will get the product collection.

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Vendor_Module
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Vendor\Module\Block\Demo;

class Index extends \Magento\Framework\View\Element\Template
{
    /**
     * Construct
     * 
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection
    ) {
        $this->productCollection = $productCollection;
        parent::__construct($context);
    }

    /**
     * Get product collection
     */
    public function getProductCollection()
    {
        $productIds = [2, 20, 1, 9, 19]; //unsorted product Ids

        $filterAttributes = [
            "entity_id",
            "name",
            "price",
            "sku",
        ];
        $collection = $this->productCollection->create()
            ->addAttributeToSelect($filterAttributes)
            ->addStoreFilter()
            ->addAttributeToFilter("entity_id", ["in"=>$productIds]);

        $cases = "CASE ";
        for ($i = 0; $i < count($productIds); $i++) {
            $cases .= 'WHEN e.entity_id = '.$productIds[$i].' THEN '.$i.' ';
        }
        $cases .= "END";

        $collection->getSelect()->order(new \Zend_Db_Expr($cases));
        return $collection;
    }
}

4. Create template file(demo.phtml) inside the app/code/Vendor/Module/view/frontend/templates/ directory. In this file, we will get the product collection from Block and display the record in the table.

Searching for an experienced
Magento 2 Company ?
Find out More
<table>
    <thead>
        <th>Product Id</th>
        <th>Name</th>
        <th>SKU</th>
        <th>Price</th>
    </thead>
    <tbody>
<?php
$collection = $block->getProductCollection();
if (!empty($collection)) {
    foreach ($collection as $each) {
?>
    <tr>
        <td><?= $each->getId() ?></td>
        <td><?= $each->getName() ?></td>
        <td><?= $each->getSku() ?></td>
        <td><?= $each->getPrice() ?></td>
    </tr>
<?php
    }
} else {
?>
    <tr><td colspan="4">No Record Found</td></tr>
<?php
}
?>
    </tbody>
</table>

5. Create Controller Index.php file inside of app/code/Vendor/Module/Controller/Demo directory.

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Vendor_Module
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Vendor\Module\Controller\Demo;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Index extends Action
{
    /**
     * @var PageFactory
     */
    protected $_resultPageFactory;

    /**
     * initialization
     *
     * @param Context $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        $this->_resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
    
    public function execute()
    {
        $resultPage = $this->_resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__("Collection"));
        
        return $resultPage;
    }
}

6. When you will hit the controller on the browser, you will get the result in the following image.

download-1-1
Collection Results in Specific Sort

Hope this will be helpful. Thanks 🙂
You can read more blogs:
Profiler in Magento2
Creating POST Method Controller in Magento 2.3
How to create custom customer address attribute in Magento 2
Inspecting developer tools in iPad Device

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home