Saturday, September 13, 2008

CF Paging Through Record Sets without URL variables

One of my clients recently asked me to avoid the use of URL variables when paging through record sets. He wanted the "clean" URL look. So I converted some code I'd written to the following.
The following code uses a hidden form and some javascript to achieve the first/next/previous/last functionality. It also displays "Showing records X - Y of Z total records"

<cfsetting enablecfoutputonly="yes">
<cfset perPage = 100>
<!--- set defaults --->
<cfparam name="session.lastStartRow" default="1">
<cfparam name="startRow" default="#session.lastStartRow#">
<cfif startRow gt qry.recordCount or startrow lt 1>
<cfset startRow = 1>
<!--- calculate next and previous starting position --->
<cfset nextStartRow = startRow + perPage>
<cfset prevStartRow = startRow - perPage>
<!--- calc the last row for display purposes --->
<cfset endRow = startRow + perPage - 1>
<cfif endRow gt qry.recordCount>
<cfset endRow = qry.recordCount>
<!--- save in case we leave the page and come back --->
<cfset session.lastStartRow = startRow>
<!--- the index of the first row of the LAST page is lastPageStart --->
<cfset lastPageStart = qry.recordCount - (qry.recordCount MOD perPage)>
<!--- output the hidden form used for navigation --->
<cfoutput><form name="frmPage" action="DataTable.cfm" method="post">
<input type="hidden" name="startRow" value="1" id="startRow">
<script language="Javascript">
function goPage(startRow) {
// update the form and submit
document.frmPage.startRow.value = startRow;
Save the navigation to a variable so we can
output it above AND Below the content easily.
<cfsavecontent variable="pager"><cfoutput>
Showing records #startRow#-#endRow# of #qry.recordCount#.
<a href="javascript:goPage(1);">First</a>  
<cfif startRow gt 1><a href="javascript:goPage(#prevStartRow#);">Previous</a><cfelse>Previous</cfif>  
<cfif endRow lt qry.recordCount><a href="javascript:goPage(#nextStartRow#);">Next</a><cfelse>Next</cfif>  
<a href="javascript:goPage(#lastPageStart#)">Last</a>
<cfsetting enablecfoutputonly="yes">

<cfoutput query="qry" maxrows="#perPage#" startrow="#startRow#">
<!--- do stuff --->

No comments: