+ Start a Discussion
dkorba2k5dkorba2k5 

Next Record and Prior Record Buttons

Thought I'd pass this little set of snipets on.  Have had clients asking us how to implement a Next and Prev button on some objects.  The concept being that if I'm looking at say an invoice I want to just easily go to the next one or previous one while still in that object instead of having to go back to the list view.  So we built the following.  The movement from one record to another is based on an invoice number field but you could modify to do it based on other fields as appropriate and you could also add a limiting factor to only records based on the owner that's running this.

 

 

VisualForce page component code


<apex:pageBlockButtons >
<apex:commandButton value="Prev" action="{!prev}" rerender="page" immediate="true" />
<apex:commandButton value="Next" action="{!next}" rerender="page" immediate="true" />
</apex:pageBlockButtons>

 

 

 

Apex controller code (this assumes you're adding to an existing controller extension class and you must initialize Allids in your init class by calling getListofIds() and we also have a generic utility that scans a list to see if it contains a field called Utils.SetContains)


Id oppid;
String invoiceno;
List <Id> Allids = new List <Id>();

 

public List<Id> getListofIds()
{
Billing__c[] billingids;
List <Id> ids = new List <Id>();

billingids = ([SELECT Id FROM Billing__c WHERE Invoice_Number__c < :invoiceno ORDER BY Invoice_Number__c DESC LIMIT 1]);
for (Billing__c b : billingids) {ids.add(b.id);}
ids.add(entry.id);
billingids = ([SELECT Id FROM Billing__c WHERE Invoice_Number__c > :invoiceno ORDER BY Invoice_Number__c LIMIT 1]);
for (Billing__c b : billingids) {ids.add(b.id);}
return ids;
}

public PageReference next()
{
Id nextid;
Integer idlocation = Utils.SetContains(System.currentPageReference().getParameters().get('id'), Allids);
if (idlocation != -1) {if (idlocation < Allids.size() - 1) {nextid = Allids[idlocation + 1];} else {nextid = AllIds[AllIds.size() - 1];}}
else {nextid = System.currentPageReference().getParameters().get('id');}
PageReference pageRef = new PageReference('/'+nextid);
pageRef.setRedirect(true);
return pageRef;
}

public PageReference prev()
{
Id previd;
Integer idlocation = Utils.SetContains(System.currentPageReference().getParameters().get('id'), Allids);
if (idlocation != -1) {if (idlocation != 0) {previd = Allids[idlocation - 1];} else {previd = AllIds[0];}}
else {previd = System.currentPageReference().getParameters().get('id');}
PageReference pageRef = new PageReference('/'+previd);
pageRef.setRedirect(true);
return pageRef;
}

 

Message Edited by dkorba2k5 on 04-27-2009 12:50 PM
withoutmewithoutme
kewl. thanks for sharing. we might end up using this on our invoice page. thanks again
clouduserclouduser

do you have the final version of the code?