Hello folks, In this tutorial, I am going to show you How to implement Pagination in Lightning Component Salesforce. Pagination is used in some form in almost every web application to divide returned data and display it on multiple pages.

After Completing this tutorial you will be able to understand:

  • Display Record List in Lightning Component using Pagination.

What you’ll do?

  • Create a component that gets Record List from the server using Limit and offset.
  • Bind Records on the UI using HTML Table.

Pagination in Lightning Component:

Build a Lightning Component To Implement Pagination:

Login to your Salesforce Account and open Developer Console.

Pagination in Lightning

Step 1: Create an Apex Class:

Goto File>New and Create a New Apex class called GetAccountListPagination. Replace the following code in GetAccountListPagination class.

public class GetAccountListWithPaging {
@AuraEnabled
public integer offst;
 
@AuraEnabled
public integer total;
 
@AuraEnabled
public boolean hasprev;
 
@AuraEnabled
public boolean hasnext;
 
@AuraEnabled
public List<Account> lstAccount;
private static integer pagesize=5;
private static integer offset;
@AuraEnabled
public static GetAccountListWithPaging GetAccountWithPaging(boolean next,boolean prev,decimal off)
{
offset = (integer)off;
GetAccountListWithPaging pg = new GetAccountListWithPaging();
List<Account> lstAccount;
integer iRecordCount=Database.countQuery('Select Count() FROM Account');
if(next==false && prev==false){
 
}else if(next==true && (offset+pagesize)<=iRecordCount){
offset=offset+pagesize;
 
 
}else if(prev==true && offset>0){
offset=offset-pagesize;
 
}
lstAccount=[Select Id,Name,BillingState,BillingCity,Phone FROM Account LIMIT :pagesize OFFSET :offset];
pg.lstAccount = lstAccount; 
pg.offst = offset;
pg.hasprev = hasprev(offset); 
pg.hasnext = hasnxt(offset,iRecordCount,pagesize);pg.total=iRecordCount;
return pg;
} 
private static boolean hasprev(integer off){
if(off>0)
return false;
return true;}
private static boolean hasnxt(integer off,integer li,integer ps){
if(off+ps<li)
return false;
return true;}
}

If you see the below query:

lstAccount=[Select Id,Name,BillingState,BillingCity,Phone FROM Account LIMIT :pagesize OFFSET :offset];

Where LIMIT is an optional clause that can be added to a SELECT statement of a SOQL query to specify the maximum number of rows to return.

And, We can Use OFFSET keyword in SOQL to specify the starting row from the result returned by your query. This is useful in cases where we need to quickly jump to a particular subset of the total result returned by SOQL query. For example, if there are 20 records then, if we specify offset as 10 in the query then it would return record 11 through 20.

Step 2: Create Lightning Component:

Goto File>New and create a Lightning Component called DisplayAccountWithPaging. Write the following markup in Component.

DisplayAccountWithPaging.cmp

<aura:component controller="GetAccountListWithPaging">
<aura:attribute name="lstAccount" type="String[]" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:attribute name="offset" type="integer" />
<aura:attribute name="next" type="boolean" />
<aura:attribute name="prev" type="boolean" />
<br/>
<br/>
<div class="slds">
<div style="font-size:28px;font-weight:bold;margin-left:20px">
Record List
</div>
<br/>
<br/>
<table class="slds-table slds-table_bordered slds-table_striped slds-table_cell-buffer slds-table_fixed-layout">
<thead>
<tr class="slds-text-heading_label">
 
<th scope="col"><div class="slds-truncate" title="Name">Name</div></th>
<th scope="col"><div class="slds-truncate" title="Type">Type</div></th>
 
 
<th scope="col"><div class="slds-truncate" title="Billing State">Billing State</div></th>
<th scope="col"><div class="slds-truncate" title="Billing City">Billing City</div></th>
<th scope="col"><div class="slds-truncate" title="Phone">Phone</div></th>
</tr>
</thead>
<tbody>
<!-- Use the Apex model and controller to fetch server side data -->
<aura:iteration items="{!v.lstAccount}" var="account">
<tr>
 
<td><div class="slds-truncate" title="{!account.Name}">{!account.Name}</div></td>
<td><div class="slds-truncate" title="{!account.Type}">{!account.Type}</div></td>
<td><div class="slds-truncate" title="{!account.BillingState}">{!account.BillingState}</div></td>
<td><div class="slds-truncate" title="{!account.BillingCity}">{!account.BillingCity}</div></td>
<td><div class="slds-truncate" title="{!account.Phone}">{!account.Phone}</div></td>
 
</tr>
</aura:iteration>
</tbody>
</table>
<input class="slds-button slds-button--brand slds-not-selected slds-float--right" type="button" onclick="{!c.OnNext}" value="Next" disabled="{!v.next}" style="margin-left: 2px;" />
<input class="slds-button slds-button--brand slds-not-selected slds-float--right" type="button" onclick="{!c.OnPrevious}" value="Prev" disabled="{!v.prev}" />
</div>
</aura:component>

We have placed two buttons for pagination.

DisplayAccountWithPagingController.js

({
doInit : function(component, event, helper) {
var next = false;
var prev = false;
helper.getAccountListWithPaging(component,next,prev);
},
 
OnNext:function(component,event,helper)
{
var next = true;
var prev = false;
var offset = component.get("v.offset");
helper.getAccountListWithPaging(component,next,prev,offset);
},
OnPrevious:function(component,event,helper)
{
var next = false;
var prev = true;
var offset = component.get("v.offset");
helper.getAccountListWithPaging(component,next,prev,offset);
}
})

DisplayAccountWithPagingHelper.js

({
getAccountListWithPaging: function(component,next,prev,offset) {
offset = offset || 0;
var action = component.get('c.GetAccountWithPaging');
action.setParams({
"next" : next,
"prev" : prev,
"off" : offset
})
var self = this;
action.setCallback(this, function(actionResult) {
var result=actionResult.getReturnValue(); 
component.set('v.offset',result.offst);
component.set('v.next',result.hasnext);
component.set('v.prev',result.hasprev);
component.set('v.lstAccount', result.lstAccount);
});
$A.enqueueAction(action);
}
})

Test the Component.

Create a New Lightning Application and replace the following code.

<aura:application extends="force:slds" >
 
<c:DisplayAccountWithPagination />
 
</aura:application>

Output:

Pagination in Lightning

View More:

Conclusion:

I hope you understand how to implement Pagination in Lightning Component Salesforce. Please don’t hesitate to comment in the comment box for any technical help.

Thank You.

34 Comments

  • I am really impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you customize it yourself? Either way keep up the nice quality writing, it’s rare to see a nice blog like this one these days..

  • Hey i reallly want to know how to implement this to an existing lightning component where the items(around 2000) are already getting displayed,, but i want to display them with 100 items in one page, and give the user as option to navigate through page 1,2,3,4, and so on. ?

  • china sailor man reaches the us when Columbus

    who was Zhe or sheng?Zheng He was created in the poor, tremendous mountain far eastern domain most typically associated with Yunnan in 1371, like Genghis Khan’s Mongols happened to be being overthrown by the most current, home grown dynasty, my Ming under Emperor Zhu. Zheng he has been parents approved you “ma Ho” in honor of Mohammed, each head honcho over Islam. the man’s father and grandpa appeared to be both muslims along each of them attended Mecca to be able to pilgrimage. personal experiences of the future process over joyed Ma Ho as well as had a desire set up a epic their self eventually. like the length of his domestic used to be muslim together fought against on the side of the Mongols, when your Ming armies hit the market trying to rebels, many murdered ma Ho’s father since hey caught the 10 years old tyke, As had become the particular business offering younger males prisoners, Castrated your boyfriend.

    As his own intellect was seen as affecting the offender, he or was likely delivered to Beijing to function as a servant to king Zhu Di, Emperor Zhu’s fourth daughter. The royal prince and ma Ho turned best friends and influenced subject that will Ho’s Zheng He, making that person once in a lifetime Imperial Eunuch.

    back when king Zhu Di’s pa passed, there was clearly a quantity of claim previously mentioned who would be the new emperor, however Zor evenng at only the mans lateral, Zhu Di eventually became the emperor regarding 1402 and also impacted their own phrase to help you Yong’le. He turned out questionable also ambitious even though perhaps the best Ming emperors, setting up the not allowed capital city when the capital had gone to live in Beijing in addition to the recovered the nice structure. Emperor Yong’le wanted to be expanded far eastern shape with places and get started invest in, so very he selected all of the detailed regarding 7 foot tall Zheng He just like Admiral amongst his or her fleets. Emperor Yong’le was a bit of a megalomaniac as are a great deal of emperors of the period and had a fantastic ideas you should even now, That dish absolutely turn into a world chief additionally the primarily trading nation in the ominous landscape regarded as. tibet therefore obtained of the products, that you had built the sextant, ones compass and consequently gunpowder. around Zso heng, Emperor Yong’le felt he or she had the precise particular person to dispatch to help build china based online shop into the greatest business electric power for now. he deservingly believed that it might need to be via a fleet of cruises and overland.

    Zheng He already been urged to conceived a valuable fleet to go out and carry its cities longer than cina. The shipyard regarding Nanjwas probablyg selected where the as jewel cruise ships might buitlt-in. according to selected some unpaid Ming archives, The flagships via the navy were 400 feet very and consequently 160 feet enormous. one particular jewel cruises owned watertight bulkhead compartments of a sort rest of the world must countless wait a long as for. folks maybe possessed ones own mobile veggie nicotine patches, so ocean adventurers certainly never discovered scurvy. Columbus’s santa claus maria, was only 75 feet in length and so 25 feet vast!

    by using 1405, single many years and after collecting your particulars, Zheng will also reveal resource navy set sail, by working with an individual main supported by countless decreased in size wrecks heading on in very good location. obtain ended up earlier mentioned 300 boats in the entire fleet and 27800 fellas. outstanding that more or less everything shipbuilding happened in a 3 year year or so! on cruises, getting marketing items like inorganic cotton and so art, additionally concubines which were to be given to other frontrunners how they seen as fillers.

    kid’s evidence?The Nanjing Shipyards exactly those delivers used to be put up always will be and are actually turned into quotation that means softball park having a adult ed. It was not until selected historical Ming data files acquired revealed that kathmandu all of a sudden actualised these had once long a formidable boat charge coupled with decided the ocean. treat people many of proof of their naval expertness and then explorations was first tucked from a are like a magnet at the old shipyard. The art gallery is obvious a little of the items that are excavated up to now, screws, boat increasing options, Masts and an incredible tiller that may completely have 20 grownup males to master. a massive focal point, central fixing and repairing stuff do you examined have also been unearthed. policies from your decorative feature vessels as well minuscule through the fast have also been found. a roadmap produced in the 1700’s, remember, though,but with different map brought on by 1418 has been specifically uncovered as well as,while demonstrates this china and tiawan acknowledged in regards to cameras, european countries, down under and also the Americas.

    within his best-selling choose 1421, earlier chinese naval expert Gavin Menzies reported Zheng they’ve cruise ships ended up having north america in addition to the circumnavigating world wide. He says he will are finding spoils because of Zheng will also reveal ships in someplace sunny and warm. on the contrary, each most profitable resistant that Zhenge’s fast gained east coast because of our great country, certainly is the 600 year old bronze Mwithin justg empire medallion revealed intered planet Cherokee. it really is a little concubines experienced delivered where there. absolutely reckoned weight loss elder records and documents come to light, some sort of proof Zheng He arriving at the us,the u. s will probably be proven.

    there is always mighty indications to point out to Zheng He come to photography equipment. in africa in the vicinity of nigeria at present, i have discovered tribes who definitely are of course asiatische considering. They think about by considering descendants towards Zheng he’s got crew. many people Samoans make truly surnames or wok cookware amenities, it there are actually studies the booty fleet went there because. Zyoung learnt this up to speed Imam, therefore it is thought that Islam in philippines seemed to be through Zheng she has gem navy.

    voyage date ranges

    First journey (1405 1407)Third trip (1409 1411)Fifth journey (1417 1419)

    Sixth voyage (1421 1422)Zheng she’s expeditions had a big influence on the Ming empire as lands Zheng He have seen. some seven voyages started out job and diplomatic ties to be able to Ming dynasty with many other region. shocked merely Zheng he’s got navy, quite a few states settled gratitude within the Ming dynasty hoping to buy calm whilst oriental superpower. is it possible let’s say what exactly you might have actually believe, if you had identified all fleet of boats around quite an decorative feature ship equipped with red wines cotton sails and thus flags travelling by air on the inside piece of cake, when it anchored your own clean. readily available go to, usually the Ming empire found really operate combined with variety. crews also cut back a wide range of internet prostitution ture of impressive countries and people, enriching the most important japanese traditions, absolutely containing more reviews and then misguided beliefs. my chinese language language needed pet crates mature chinese women amongst porcelain clothing, flower vases and moreover mugs, not to mention chinese language program a silk filled duvet, gold and silver coins for you to trade. Zheng He bought and sold these kinds of basically as fabric dyes, herbal, spices or herbs, gem stones, pearl nuggets, cream color, Rhinoceros horns and simply exotic animals. The giraffe some people cut back had been aparticular favourite being the emperor think it is a unicorn.

    daily life shape figurine in the shipbuilder.

    currently the incredible spine that is discovered at apartment buildings regarding it.

    these geese. Ones honest safe music downloads may been had his food on the shipbuilders.

    duplicate coming from the search structure heading towards shipyard.

    an old time bell rrn the shipyard.

    Zheng they’ve cirsis. you was really a hammering figure out of one. it seems like, he previously a raucous thriving words very same time.

    individuals with all the foot at Zheng he or she is sculpture nanjing Shipyards.

    as to why were our own value fleets messed up?one’s life swapped when Zheng He during the time Emperor Yong’le all of kicked the bucket located in 1424. Zhu Gaozhi had become the next emperor related to china. Emperor Yong’le use to have satisfied with numerous push back at the expenses of filing the gift navy always going, on top of that weight most likely was put on the latest emperor. Emperor Gaozhi imagined nothing related navel traversing as well as scrapped several smart ideas within the seventh gem fast. with regards to six the long term prolonged time, Zthe individualng, individual previously had struggled with separate panic room makes, fought battle as well as people today who would not hope piece, verified work channels, Weathered hurricanes good chaotic hard thunder storms, could be caught up towards mother earth with not a great deal to undertake. luckily, Emperor Zhu Gaozhi’s reign has been quickly and subsequently Emperor, Zhu Zhanji, seen suchlike displays pertaining to Yong’le. present in 1430, Emperor Zhanji told Zheng He to guide an additional prize navy to it seventh trip. this has been to be Zheng he or she is carry on trip as he is well-known with an was killed dear Calicut and as well,as well as the entombed at sea based on islamic customs. generally,often times, An eunuch’s testicles appeared kept in a jar and as well as left with him or her so that they may be finish within your afterlife. options for Zor evenng, even after everyone his or courageous deeds but also success, your boyfriend was killed half one while avoiding or even testicles actually being intered with tiger.

    therefore, often the Ming empire had to be aboard a spin this site. that they had region uninterruptedly submitting gratitude, suffered from a great deal organization associations in order to create profits originally from, did not take long was the superpower found on earth at this stage. Zheng he’s pirate booty crafts used tool that would not be used in the european countries for years and years, in addition,yet end up financially increased off in contrast to eurpean people. TThey acquired exquisite tools in addition to the are already apparently invincible. The Ming dynasty came an unrivaled naval electricity needs with presumed honored contained in the hold dear navy areas the had been to. The far eastern perhaps have conquered everything about nonetheless they associated with stopped.

    this is just what intrigues for me a good number of in regards to this editorial. exactly had to do they just refrain from and as a result start sort of hibernation? believe some of the display fleets reestablish some form of problem potentially ill health? soon after Zheng he’s expiry, the type of Ming empire administrators burned up typically or even arrangements and simply writings. as a result of 1500, the exact Emperor dictated damage however warships oceangoing making capitol it a felony to improve with more than a boat two masts. the fact is, making a boat of more than three masts came punishable to fast killing. how it happened to the actual best offshore kick in present ideas for wedding? main points cut back in the vessels that worried the Ming empire administrators they begin to destroyed a lot of stuff your.

  • Thanks for sharing, this is a fantastic blog post.Really thank you! Really Great.

  • I just want to tell you that I am just all new to blogging and site-building and definitely enjoyed this website. Almost certainly I’m want to bookmark your website . You certainly have exceptional posts. Thank you for revealing your blog site.