kallakafar
kallakafar

Reputation: 735

ColdFusion - Can cfoutput list all columns in the table without explicitly listing the column names?

Is there a way by which the cfoutput can select all columns from the table and display on the webpage using a HTML table? I have a database table with a large number of columns, and I do not want to list out each column name in either cfquery or cfoutput part of the cfm webpage.

Example: Let's say Table1 has 26 columns - A,B,C,D,E....X,Y,Z. I wish not to specify these column names explicity, in cfoutput while building the HTML table. Instead prefer to dynamically build the table so that all columns that are in Table1 are presented as a table.

<CFQUERY NAME="query1" DATASOURCE="abcd">
select a,b,c,....,x,y,x from table1
</CFQUERY>

Now in the table part of webpage:

<TABLE>
                    <TR> 
                        <TH>A</TH> 
                        <TH>B</TH>
                        <TH>..</TH>
                        <TH>Y</TH>
                        <TH>Z</TH>
                    </TR>   

                    <CFOUTPUT query="query1">
                    <TR align="center">
                        <TD>#a#</TD>
                        <TD>#b#</TD>
                        <TD>#...#</TD>
                        <TD>#y#</TD>                        
                        <TD>#z#</TD>                        
                    </TR>
                    </CFOUTPUT>
                </TABLE>

My actual tables would have quite a large number of columns. It would be easy to build the table dynamically rather than manually listing it. Any suggestions, much appreciated!

Upvotes: 0

Views: 2191

Answers (1)

Dan Bracuk
Dan Bracuk

Reputation: 20794

Here is another way.

fields = "Field1,Field2,etc";
columnHeaders = "Header 1,Header 2,etc"'

<cfquery name = "yourQuery">
select #fields#
etc
</cfquery>

<tr><cfoutput><cfloop list = columnHeaders index = "header">
<th>#header#</th>
</cfloop></cfoutput></tr>
<cfoutput query = "yourQuery">
<tr>
<cfloop list = fields index = "field">
<td>#yourQuery[field][currentrow]#</td>
</cfloop>
</tr>
</cfoutput>

If you need to do things like format dates, right align numbers, and such, it gets a little complicated.

Upvotes: 1

Related Questions