In case you want to add pagination in a custom collection, you may require to size of each page. That’s where you can use the setPageSize method in Magento 2.
In this quick guide, you’ll learn what is setPageSize method and how you can use it.
What is setPageSize in Magento 2?
The setPageSize method in Magento 2 is used to control the number of items (like products, customers, or orders) displayed on a page in your online store. This is helpful to limit the page size when you’re creating pagination for a custom collection.
In addition to pagination, the setPageSize is also used to limit the number of items in admin grids, product listings, and search results.
The setPageSize Syntax
Typically, the method is used with the collection object as follows:
$collection->setPageSize($pageSize);
In the above syntax, the setPageSize method assigns the maximum number of records for each page in the collection object. Here, we have assigned the $pageSize variable. However, you can also pass static integer values.
For example, the following code:
$collection->setPageSize(10);
will limit the maximum number of records per collection to 10.
That’s how easily you can use setPageSize in Magento 2 to limit the number of items per collection. I hope you’ll find this tutorial helpful. In case you have any further queries or doubts, feel free to leave a comment.