user3440142
user3440142

Reputation: 35

Looping Columns in coldfusion along with values in correct order

Instead of hardcoding the columns from a query into a table I prefer to do it dynamically. This is code I tweaked from another source. What I want to do is not only get the Columns in order, but also get the row values for each column as well. I can't seem to find an attribute that shows the actual row values for each column using this method, just the column names and type.

In the two cfloops the top one will represent the column name, while the bottom one will present the row value for that column.

cfset employeemeta=getMetaData(ShowDeletedData)>
 <Table border="1">
 <TR>
<h4>The Employees table has the following columns</h4>
<cfloop index="i" from="1" to="#arrayLen(employeemeta)#">
    <cfoutput>
       <TD> #employeemeta[i].name# </TD>
    </cfoutput>
</cfloop>
</TR>
 <TR>
<cfloop index="i" from="1" to="#arrayLen(employeemeta)#">
    <cfoutput>
       <TD> #employeemeta[i].name# </TD>
    </cfoutput>
</cfloop>
</TR>
</table>

Upvotes: 0

Views: 2293

Answers (2)

Dan Bracuk
Dan Bracuk

Reputation: 20804

Something I learned from other people's answers on these forums is that ColdFusion has a function called getColumnList(). It returns an array of the column names in the order they appear. I just ran this code to verify it.

<cfquery name="x" datasource="burns">
select 1 b, 2 a
from dual
</cfquery>
<cfdump var="#x.getcolumnlist()#" metainfo="no">

It returned an array showing b, then a.

For displaying your column headers, you simply loop through this array. Displaying the data would be slightly more complicated. I would do something like this:

<cfoutput query="q1">
<cfloop array="#q1.getcolumnlist()#" index = "arrayElement">
#q1[arrayElement][currentrow]#
closing tags

Upvotes: 5

Adam Cameron
Adam Cameron

Reputation: 29870

This answer seems too obvious to be the answer to your requirement, but I can't think what else you might mean. One loops over a recordset via the <cfloop> tag:

<cfloop query="showDeletedData"><!--- loop rows--->
    <cfloop array="#employeemeta#" index="col"><!--- loop columns--->
        <cfoutput>#showDeletedData[col][currentRow]#</cfoutput><!--- output value for the row/column --->
    </cfloop>
</cfloop>

Is that what you're asking?

Upvotes: 2

Related Questions