Wednesday, July 16, 2008

pagination in coldfusion

Previous / Next n Records
This tutorial will demonstrate how to incorporate a navigation system the displays next X records per page. Not sure what I mean? Take a look at the same below:
 Previous 5 records
Next 5 records 


This example will demonstrate how to incorporate it into your query results. The first thing we must do is define two variables:
The first variable we're defining by default is "Start". We're giving this a value of 1. The variable "start" will be used to let the ColdFusion server know which record we will want to begin at to display on the current page. The next variable is "disp", this variable will let ColdFUsion server know how many records to display per page. You can make this value any number you want.
<!--- Start displaying with record 1 if not specified via url --->
<CFPARAM name="start" default="1">
<!--- Number of records to display on a page --->
<CFPARAM name="disp" default="5">

The varaible displayed above will make the magic appear, next let's query the database for all records:
<!--- Fetch records --->
<CFQUERY name="data" datasource="MyDB">
SELECT MyField
FROM MyDB
ORDER BY MyField
</CFQUERY>

Ok, now that you have your database queried and you've defined where to start and how many rows to display, we're ready to begin displaying the data on the page:
<CFSET end=Start + disp>
<CFIF start + disp GREATER THAN data.RecordCount>
<CFSET end=999>
<CFELSE>
<CFSET end=disp>
</CFIF>

<CFOUTPUT query="data" startrow="#start#" maxrows="#end#">
#CurrentRow#. #MyField#<br>
</CFOUTPUT>
<CFOUTPUT>
<br>
<table border="0" cellpadding="10">
<tr>
<!--- Display prev link --->
<CFIF start NOT EQUAL 1>
<CFIF start GTE disp>
<CFSET prev=disp>
<CFSET prevrec=start - disp>
<CFELSE>
<CFSET prev=start - 1>
<CFSET prevrec=1>
</CFIF>
<td><font face="wingdings">ç</font> <a
href="NextN.cfm?start=#prevrec#">Previous #prev#
records</a></td>

</CFIF>
<!--- Display next link --->
<CFIF end LT data.RecordCount>
<CFIF start + disp * 2 GTE data.RecordCount>
<CFSET next=data.RecordCount - start - disp + 1>
<CFELSE>
<CFSET next=disp>
</CFIF>
<td><a href="NextN.cfm?start=#Evaluate("start + disp")#">Next
#next# records</a> <font face="wingdings">è</font></td>
</cfif>
</table>
</CFOUTPUT>

That's it! That's all there is to adding " Previous/Next 'X' " into your website..

1 comment:

Edson said...

hi, thanks for the code but i have a problem, my query is dynamic like these:


SELECT LICITACION, ESTADO, LOCALIDAD, TIPO, DESCRIPCION, RUBRO, ESTUDIOS, PROYECTO,
CATALOGO_CONCEPTOS, MATRIZ_MUDA, ESPECIFICACIONES, RUTA
FROM catalogo
where DEPENDENCIA LIKE 'API VER'


AND Tipo LIKE '%#FORM.Tipo#%'




and rubro like '%#FORM.Rubro#%'


********************
Son when i clic the next page i lost the values of my form variables

can you help me please!! ??