:::: MENU ::::
Posts tagged with: custom

Magento 2 get latest order collection

Today we learn how to get latest order collection. You can simply add the setOrder entity_id to DESC or use created_at to DESC to your order collection. If you want to add limit simply add setpagesize


protected $_orderFactory;
public function __construct(

\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderFactory,


$this->_orderFactory = $orderFactory;

public function getLatestOrders() {
$orderCollection =$this->_orderFactory>create()->addFieldToSelect(array('*')); $orderCollection>setOrder('entity_id','DESC');
return $orderCollection;
Author: Qaisar Satti
Category: Magento 2
Last Modified: November 6, 2017

Magento 2 add pagination on custom collection

Today, we’ll talk about how to get custom collection with magento 2 default pagination or use pager with custom collection.For any suggestions & question, please feel free to drop a comment.

First Step:

Get collection for pagination.

public function getNews() {
 //get values of current page
$page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
 //get values of current limit
$pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 1;
$newsCollection = $this->newscollectionFactory->create(); $newsCollection->addFieldToFilter('is_active',1); $newsCollection->setOrder('title','ASC'); $newsCollection->setPageSize($pageSize); $newsCollection->setCurPage($page);
return $newsCollection;

Second Step:
Now simply add the pagination to you collection

protected function _prepareLayout() {
 if ($this->getNews()) {
$pager = $this->getLayout()->createBlock( 'Magento\Theme\Block\Html\Pager', 'qaisarsatti.news' )->setAvailableLimit(array(5=>5,10=>10,15=>15))->setShowPerPage(true)->setCollection( $this->getNews() );
$this->setChild('pager', $pager);
return $this;

Third Step:
Now create a function to get the child block of pager.

public function getPagerHtml() {
return $this->getChildHtml('pager');

Fourth Step:
in your phtml file add this code then pagination will be showing with limits.

<?php if ($block->getPagerHtml()): ?>
<div class="order-products-toolbar toolbar bottom">
<?php echo $block->getPagerHtml(); ?>
<?php endif ?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: December 29, 2017