0

I am converting an Array to Magento2 Collection

        $items = $this->getItems();
        $collection = $this->collectionFactory->create();
        foreach ($items as $item) {
        $varienObject = new \Magento\Framework\DataObject();
        $varienObject->setData($item);
        $collection->addItem($varienObject);
        }
        return $collection

Now When I apply pagination on this collection

        $pager->setLimit(5)->setShowPerPage(true);

Not working it is showing all the records on one page although setavailable limit is showing correct values.

enter image description here

Here is my code for applying pagination

    if ($this->Test()) {
        $pager = $this->getLayout()->createBlock('Magento\Theme\Block\Html\Pager', 'productpartsfinder.bysize.pager')->setAvailableLimit(array(5 => 5, 10 => 10, 15 => 15, 20 => 20));
        $pager->setLimit(5)->setShowPerPage(true);
        $pager->setCollection($this->Test());
        $this->setChild('pager', $pager);
        $this->Test()->load();
    }
    return parent::_prepareLayout()

2 Answers 2

1

Try below code to Convert an array to a collection in magento2:

$dataArray = [];
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$collection = $objectManager- >create('Magento\Framework\Data\Collection');

foreach ($dataArray as $key => $row) {
   $varienObject = new \Magento\Framework\DataObject();
   $varienObject->setData($row);
   $collection->addItem($varienObject);
}
return $collection;
0

For limiting a collection use setPageSize() and setCurPage() methods:

$collection 
    ->setPageSize(5) // only get 5products 
    ->setCurPage(1)  // first page (means limit 0,10)
    ->load(); 
1
  • I have already added this in my code but still it is not working Commented Mar 3, 2022 at 5:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.