Reading list Switch to dark mode

    Magento 2 Development 11: Filter and Sorting

    Updated 6 March 2024

    We have displayed the blog list but it will show all the blogs. Even if we create a new customer s/he will be able to see the blogs from the previous customer. So to fix this issue we need to filter our Data.

    Filter

    If you think in terms of SQL query then you can use WHERE user_id=$customerId but in Magento we do not write raw SQL queries. To apply conditions on the collection we have to use the addFieldToFilter method. Let’s check out the code for a better understanding, we have to edit the Block/BlogList.php because we are sending the data from here only,

    Updated code for Block/BlogList.php file

    <?php
    namespace Webkul\BlogManager\Block;
    
    use Magento\Customer\Model\SessionFactory;
    
    class BlogList extends \Magento\Framework\View\Element\Template
    {
        /**
         * @var \Webkul\BlogManager\Model\ResourceModel\Blog\CollectionFactory
         */
        protected $blogCollection;
    
        /**
         * @var Magento\Customer\Model\SessionFactory
         */
        protected $customerSession;
    
        /**
         * Dependency Initilization
         *
         * @param \Magento\Framework\View\Element\Template\Context $context
         * @param \Webkul\BlogManager\Model\ResourceModel\Blog\CollectionFactory $blogCollection
         * @param array $data
         */
        public function __construct(
            \Magento\Framework\View\Element\Template\Context $context,
            \Webkul\BlogManager\Model\ResourceModel\Blog\CollectionFactory $blogCollection,
            SessionFactory $customerSession,
            array $data = []
        ) {
            $this->blogCollection = $blogCollection;
            $this->customerSession = $customerSession;
            parent::__construct($context, $data);
        }
    
        /**
         * Get Blog List
         *
         * @return \Webkul\BlogManager\Model\ResourceModel\Blog\Collection
         */
        public function getBlogs()
        {
            $customerId = $this->customerSession->create()->getCustomer()->getId();
            $collection = $this->blogCollection->create();
            $collection->addFieldToFilter('user_id', ['eq'=>$customerId]);
            return $collection;
        }
    }
    Selection_110

    Here we have used the customer session to get the customer id. Now please take note of ->addFieldToFilter(‘user_id’, [‘eq’=>$customerId]); in the first param, we have passed the column name. And in the second param, we have passed an associative array, whose key represents the operators. eq means equal operator. Some other important operators are,
    [“eq” => $equalValue]
    [“neq” => $notEqualValue]
    [“like” => $likeValue]
    [“in” => [$inValues]]
    [“nin” => [$notInValues]]
    [“notnull” => $valueIsNotNull]
    [“null” => $valueIsNull]
    [“gt” => $greaterValue]
    [“lt” => $lessValue]
    [“gteq” => $greaterOrEqualValue]
    [“lteq” => $lessOrEqualValue]
    [“from” => $fromValue, “to” => $toValue]

    If we do not provide any operator then it just uses the equal operator, which means here we can use ->addFieldToFilter(‘user_id’, $customerId) also.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    To combine multiple conditions with the AND operator we have to use multiple addFieldToFilter methods. So for example, WHERE (`user_id` = ‘1’) AND (`status` != 0) can be achieved with following code,

    $collection->addFieldToFilter('user_id', $customerId)
               ->addFieldToFilter('status', ['neq'=>0]);

    Sorting

    It will be better from a usability standpoint if we show the latest blogs at the top. In SQL we use ORDER BY to sort. Let’s see how can we sort in Magento, we have to edit the Block/BlogList.php

    Updated code for Block/BlogList.php file

    <?php
    namespace Webkul\BlogManager\Block;
    
    use Magento\Customer\Model\SessionFactory;
    
    class BlogList extends \Magento\Framework\View\Element\Template
    {
        /**
         * @var \Webkul\BlogManager\Model\ResourceModel\Blog\CollectionFactory
         */
        protected $blogCollection;
    
        /**
         * @var Magento\Customer\Model\SessionFactory
         */
        protected $customerSession;
    
        /**
         * Dependency Initilization
         *
         * @param \Magento\Framework\View\Element\Template\Context $context
         * @param \Webkul\BlogManager\Model\ResourceModel\Blog\CollectionFactory $blogCollection
         * @param array $data
         */
        public function __construct(
            \Magento\Framework\View\Element\Template\Context $context,
            \Webkul\BlogManager\Model\ResourceModel\Blog\CollectionFactory $blogCollection,
            SessionFactory $customerSession,
            array $data = []
        ) {
            $this->blogCollection = $blogCollection;
            $this->customerSession = $customerSession;
            parent::__construct($context, $data);
        }
    
        /**
         * Get Blog List
         *
         * @return \Webkul\BlogManager\Model\ResourceModel\Blog\Collection
         */
        public function getBlogs()
        {
            $customerId = $this->customerSession->create()->getCustomer()->getId();
            $collection = $this->blogCollection->create();
            $collection->addFieldToFilter('user_id', ['eq'=>$customerId])->setOrder('updated_at', 'DESC')   ;
            return $collection;
        }
    }

    To sort we use the setOrder method where in the first param we have to pass the column name and in the second we have to mention whether we want to sort in ascending or descending order. Here we are updating based on the updated_at column so the latest updated blogs will come at the top.

    Selection_111

    Here you can see that the latest blog is coming at the top. Also, we are seeing only those blogs which have user_id the same as the current customer id.

    PS. We can view the actual SELECT query for the collection by printing the $collection->getSelect();

    We have not created any files so the folder structure will remain the same.

    Selection_112
    Folder Structure

    Next Blog -> Magento 2 Development 12: Editing and Updating

    Previous Blog -> Magento 2 Development 10: Collection and Block

    . . .

    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