How to Implement Pagination in Salesforce Visualforce Pages? : Abhijeet

How to Implement Pagination in Salesforce Visualforce Pages?
by: Abhijeet
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary of Pagination in Salesforce Visualforce Pages **What is Pagination in Salesforce?** Pagination is a feature in Salesforce that helps organize large sets of records by dividing them into smaller, manageable pages. This improves user experience and performance when dealing with extensive datasets. **How to Implement Pagination in Visualforce Pages:** 1. **Create a Controller:** First, create an Apex class (controller) that manages data retrieval and pagination logic. The controller will define parameters such as `pageSize`, `currentPage`, `totalRecords`, and `totalPages`. It fetches records from the Account object and provides methods to navigate between pages. 2. **Visualforce Page Creation:** Next, create a Visualforce page that uses the controller. This page will display account records in a table format and include "Previous" and "Next" buttons for navigation. 3. **Using StandardSetController:** Alternatively, you can implement pagination using the `StandardSetController`, which provides built-in methods for pagination, making it easier to manage without writing manual logic. ### Key Details: - **Manual Pagination:** Involves creating a custom controller to handle data fetching and navigation. - **StandardSetController:** Offers automatic pagination with predefined methods for navigation. - **User Interaction:** Users can navigate through pages using buttons, and the number of records displayed per page can be set (e.g., 10 records). ### Conclusion: Understanding and implementing pagination in Salesforce Visualforce pages is crucial for handling large datasets efficiently. Depending on your needs, you can choose between manual pagination for custom logic or `StandardSetController` for straightforward use cases. ### Additional Context: Pagination is essential for improving the performance of applications that display large volumes of data, making it easier for users to find and interact with the information they need. ### Hashtags for SEO: #Salesforce #Visualforce #Pagination #Apex #SalesforceDevelopment #DataManagement #UserExperience #StandardSetController #SalesforceTutorial #CRM


In Salesforce, using Pagination in Visualforce pages allows us to display a large set of records in manageable sets. This feature is helpful when working with large datasets in Salesforce org.

In this Salesforce tutorial, we will learn about pagination and how we can use pagination in Salesforce.

What is Pagination in Salesforce?

In Salesforce pages, we can divide content into separate pages by using pagination. In Salesforce, when the fetched data is collected in large datasets, displaying all records on a single page can make the page look unorganized to users and lead to performance issues. Pagination solves this by showing only a subset of records per page, allowing users to navigate through pages easily.

Implement Pagination in Salesforce Visualforce Pages

To implement pagination in Salesforce pages, we need an object with a large set of data. In this example, I will use the data of the Account object to create pagination and display the account records.

1. First, we will create a visualforce controller to manage data retrieval and navigation logic for the pagination.

Click on File > New > Apex Class, then label the controller class and enter the code below.

public class PaginationController {
    public List<Account> accounts { get; private set; }
    public Integer pageSize { get; set; }
    public Integer currentPage { get; private set; }
    public Integer totalRecords { get; private set; }
    public Integer totalPages { get; private set; }

    public PaginationController() {
        pageSize = 10; 
        currentPage = 1; 
        fetchData();
    }

    public void fetchData() {
        totalRecords = [SELECT Count() FROM Account];
        totalPages = (Integer)Math.ceil((Double)totalRecords / pageSize);

        accounts = [SELECT Id, Name, Industry FROM Account 
                    ORDER BY Name 
                    LIMIT :pageSize 
                    OFFSET :((currentPage - 1) * pageSize)];
    }

    public void nextPage() {
        if (currentPage < totalPages) {
            currentPage++;
            fetchData();
        }
    }

    public void previousPage() {
        if (currentPage > 1) {
            currentPage--;
            fetchData();
        }
    }
}

In this controller class, we have parameters such as pageSize, CurrentSize, totalPages, and totalRecords. The “total records” will store the total count of records retrieved from the database, and “totalPages” will calculate the total number of pages needed for pagination.

Then, to fetch the records, we have the method “fetchData“, and in this method, the query [SELECT Count() FROM Account] will count the records, and the parameter (Integer)Math.ceil((Double)totalRecords / pageSize) will count the total number of pages.

After this, the query below will calculate the fetched records and the number of pages required, and then it will display the records on each page according to the set limit.

[SELECT Id, Name, Industry FROM Account 
                ORDER BY Name 
                LIMIT :pageSize 
                OFFSET :((currentPage - 1) * pageSize)]

3. After this, we will create the Visualforce page using the code below.

<apex:page controller="PaginationController">
    <apex:form>
        <apex:pageBlock title="Accounts Pagination">
            <apex:pageBlockTable value="{!accounts}" var="acc">
                <apex:column value="{!acc.Name}" headerValue="Account Name"/>
                <apex:column value="{!acc.Industry}" headerValue="Industry"/>
            </apex:pageBlockTable>
            
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Previous" action="{!previousPage}" disabled="{!currentPage == 1}" />
                <apex:commandButton value="Next" action="{!nextPage}" disabled="{!currentPage == totalPages}" />
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

On the visualforce page, we have used the <apex:pageBlockTable> to display the data in the table format. In the component <apex:pageBlockButtons>, we have defined the navigation logic between the pages.

4. After creating the controller and visualforce page, we will navigate to the visualforce setup and view the preview.

To navigate there, go to setup> visualforce pages, select the pagination visualforce page, and click on the Preview Layout in the next window.

In the visualforce page preview, we can see that according to the defined logic in controller “pageSize = 10“, the page displays 10 records on each page, and using the Previous and Next buttons, we can navigate to the pages and view all fetched records.

Create Pagination in Salesforce Visualforce Pages

This way, we can add pagination to visualforce pages in Salesforce by following the above method.

Implement Pagination on Visualforce pages with StandardSetController.

Another method to implement pagination in Salesforce visualforce pages is using the StandardSetController. In the previous method, we have defined the manual logic for dividing records into pages and also for the navigation button.

By using the StandardSetController we get built-in functionality that handles pagination automatically, and for navigation, it has predefined methods like next() and previous().

1. Now, execute the below code to add pagination to a visualforce page using the StandardSetController method.

<apex:page controller="PaginationWithSSCController">
    <apex:form>
        <apex:pageBlock title="Pagination with StandardSetController">
            <apex:pageBlockTable value="{!records}" var="record">
                <apex:column value="{!record.Name}" />
                <apex:column value="{!record.Industry}" />
                <apex:column value="{!record.Rating}" />
            </apex:pageBlockTable>

            <apex:pageBlockButtons location="bottom">
                <apex:commandButton action="{!previous}" value="Previous" disabled="{!!setController.hasPrevious}" />
                <apex:commandButton action="{!next}" value="Next" disabled="{!!setController.hasNext}" />
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

In the StadardSetController, we have inbuilt methods like “previous“, “next“, “hasnext“, and “hasprevious” to manage the pagination logic.

2. After this, create the controller class that will handle the logic for the visualforce page.

Controller class:

public with sharing class StandardPaginationController {
    public ApexPages.StandardSetController setController { get; private set; }
    public List<Account> records { get; private set; }

    public StandardPaginationController() {
        List<Account> allRecords = [SELECT Id, Name, Industry, Rating FROM Account ORDER BY Name];
        
        setController = new ApexPages.StandardSetController(allRecords);
        
        setController.setPageSize(10);
        
        updateRecords();
    }

    private void updateRecords() {
        records = (List<Account>) setController.getRecords();
    }

    public void previous() {
        setController.previous();
        updateRecords();
    }
    public void next() {
        setController.next();
        updateRecords();
    }
}

In the setPageSize, we can set the number of records to display per page.

3. After creating the visualforce page and the controller, navigate to the visualforce page setup and open the visualforce page in the Preview layout.

In the preview layout, you will see the pagination created after fetching the records of the Account object, displaying the table columns Account Name, Industry, and Rating.

Pagination with StandardSetController in Salesforce visualforce

In this way, we can implement built-in pagination for Visualforce pages in Salesforce using StandardSetController.

Both the above methods are efficient in adding pagination to the visualforce pages, and you have to choose them according to the requirements.

When you need custom logic like dynamic sorting, filtering, or other interactive features, you need to process only small data from the database simultaneously. Then, you can go with the manual pagination.

While having a simple use case requiring basic pagination, where the method should handle the pagination logic by itself, you can use StandardsSetController pagination.

Conclusion

In this Salesforce tutorial, we learned about pagination concepts and how to implement pagination on Salesforce Visualforce pages. We have discussed about two pagination methods; one is the manual method, where we defined the logic for fetching the data and navigation of pages. After this, we implemented the pagination on visualforce pages using the standard method SetStandardController.

You may also like to read:

The post How to Implement Pagination in Salesforce Visualforce Pages? appeared first on SalesForce FAQs.


January 01, 2025 at 07:17PM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Abhijeet
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce