Fancy Table Layouts in Coldfusion

Posted by Mark Drew on code on January 22, 2005

Tagged under coldfusion

Am interesting question come up in the cf-talk mailing list: I have a query with x number of records. I want to dynamically create a table on my display that displays five records per row, ie (qf = queryfield):

qf spacer qf spacer qf spacer qf spacer qf
qf spacer qf spacer qf spacer qf spacer qf

and so on…

Also need to know how to fill in empty cells on the last row if my recordcount isn’t divisible by 5. Can anyone point me to an article/tutorial/code snippet which could show me how to do this efficiently? </i>

My response is below, I am using a list just for demonstration but you can change it yourself to loop through a query with the basics in place.

//We set a list of words we are going to loop over <cfset lWords = "eine, meine, miney, mo, catch, developers, by, their, toe"> <cfset nLength = ListLen(lWords)> //The number of columns we want (this is a word and spacer) <cfset columns = 5> //Now, we check how many rows there would be , I do a ceiling function so that I get the upper integer e.g. //if we have 9 items, and we have 4 columns, we shall have 3 rows, the last row having one item and 3 blanks <cfset rows = Evaluate(ceiling(nLength

/columns))> //the ideal number of records that we shall have in TOTAL (including empty ones) in the table <cfset idealrecords = Evaluate(rows * columns)> <cfoutput> Number of items = #nLength#<br /> Number of columns = #columns# <br /> Number of Rows = #rows#<br /> Ideal Number of Columns = #idealcols#<br /> <table border="1" width="80%"> <tr> //Loop from 1 to the ideal total number of items (never mind rows) <cfloop from="1" to="#idealcols#" index="i"> //We set if this column needs a row <cfset colCounter = i MOD columns> //make sure that we dont need an empty space <cfif i LTE ListLen(lWords)> <td>#ListGetAt(lWords, i)#</td> <cfelse> <td> </td> </cfif> //Insert a row if required <cfif colCounter EQ 0> //Unless we are at the end of the list (we already have a TR <cfif i LT idealcols> </tr> <tr> </cfif> <cfelse> <td> </td> </cfif> </cfloop> </tr> </table> </cfoutput>

What this gives you is:

eine spacer meine spacer miney spacer mo spacer catch
developers spacer by spacer their spacer toe spacer blank cell

you can change the <cfset columns = 5> to change the number of columns and the code should still work

Let me know if this helpful to you!




comments powered by Disqus