Need advice.. dynamic td tr - coldfusion

Hi am doing dynamic TR and TD in coldfusion, but apparently i am trying this kind of screen. here is my try with colfusion
<cfif variables.newrow EQ true>
<tr align="center">
</cfif>
<cfoutput query="gResults">
<cfquery datasource="#request.dsn#" name="nextqueries">
Query
</cfquery>
<td height="30" valign="middle"><strong>
<a href="viewdir.cfm?catID=#val(pic_id)#
<cfif isDefined('url.l') and url.l neq ''>&l=#url.l#</cfif>">
#pic_cat_name#</a></strong><br>
<cfloop query="nextqueries">
<cfquery datasource="#request.dsn#" name="showanother">
select * from
mytable as grlist
where pic_cid =
<cfqueryparam cfsqltype="cf_sql_numeric" value="#Trim(nextqueries.pic_id)">
</cfquery>
»
<a href="viewdir.cfm?catID=#val(pic_id)#
<cfif isDefined('url.l') and url.l neq ''>&l=#url.l#</cfif>">#pic_cat_name#
</a> </cfloop></td>
<cfif gResults.currentRow MOD 4 EQ 0>
</tr>
<cfset variables.newrow = true>
<cfelse>
<cfset variables.newrow = false>
</cfif>
</cfoutput>
trying to do like this:
http://screencast.com/t/oso4jkhBm3

There are a lot of potential improvements, but this answer will only deal with table rows. You start with:
<cfif variables.newrow EQ true>
<tr align="center">
</cfif>
Now I'm going to look for the closing tag. The only one I see is here:
<cfif gResults.currentRow MOD 4 EQ 0></tr></cfif>
and that line is inside a query loop. What this means is that you might have more than one closing tag, or you might not have any. You need exactly one. To solve this specific problem, you have to do this:
<cfif variables.newrow EQ true>
<tr align="center">
code to populate this table row
</cfif>
When you get that part sorted out, we can look at what goes into the details.

To get data to display in an html table from top to bottom then left to right like in the image linked in your question, you can do something similar to the following.
<!--- Get query results --->
<cfset arrayOFValues = arraynew(1)>
<cfset queryResults = querynew("Col1,Col2,Col3")>
<!--- Fill query with example data --->
<cfloop from="1" to="25" index="i">
<cfset queryaddrow(queryResults)>
<cfset querySetCell(queryResults, "Col1", "Col1 Row " & i)>
<cfset querySetCell(queryResults, "Col2", "Col1 Row " & i)>
<cfset querySetCell(queryResults, "Col3", "Col1 Row " & i)>
</cfloop>
<!--- Now have a query named queryResults with 25 rows --->
<!--- Set the number of columns and calculate the number of rows needed --->
<cfset numberOfColumns = 3>
<cfset rowsNeeded = ceiling(queryResults.recordcount / numberOfColumns)>
<cfoutput>
<table>
<cfloop from="1" to="#rowsNeeded#" index="curRow">
<tr>
<cfloop from="0" to="#numberOfColumns-1#" index="curCol">
<td>
#queryResults.Col1[(rowsNeeded * curCol) + curRow]#
</td>
</cfloop>
</tr>
</cfloop>
</table>
</cfoutput>
The first part is just creating a query result. I then find the number of rows that is needed to display the records by dividing the number of results returned in the query by the number of columns to be displayed. The ceiling is required for when the result is not a whole number.
We have to loop each column record with in the row to get the desired index. To find the required index of the field we have to take the row that’s being displayed + the column were on times the the number of rows that will be displayed.
If you know the number of columns you can hard code for them in the following manner and eliminate the inner loop.
<tr>
<td>#queryResults.Col1[3 * rowsNeeded]#</td>
<td>#queryResults.Col1[3 + 1*rowsNeeded]#</td>
<td>#queryResults.Col1[3 + 2*rowsNeeded]#</td>
</tr>

Related

CF sum of percentage column

I am having lots of trouble creating the sum of my percentage column which seems like it would be easy since its 100% when all branches are being shown. But I need to figure out the equation for the times that all branches are not shown. In the picture below each branches percentage is calculated by the number of that locations processed checklists divided by the total number of checklists. Unfortunately I can not figure out how to just "write" just adding the sum of the percentage column and displaying in into the total column. Any help would be greatly appreciated.
<cfset result = {} />
<cftry>
<cfquery datasource="#application.dsn#" name="GetLocationInfo">
SELECT *
FROM cl_checklists
</cfquery>
<cfquery name="allLocCode" dbtype="query">
SELECT DISTINCT trans_location, COUNT(*) AS locationCount FROM GetLocationInfo Where trans_location is not null GROUP BY trans_location ORDER BY trans_location
</cfquery>
<cfcatch type="any">
<cfset result.error = CFCATCH.message >
<cfset result.detail = CFCATCH.detail >
</cfcatch>
</cftry>
<cfset columnSum = ArraySum(allLocCode['locationCount'])>
<table border="1" id="Checklist_Stats">
<thead>
<th><strong>Location</strong></th>
<th><strong>Percent of Total Checklists</strong></th>
<th><strong>Location Total</strong></th>
</thead>
<tbody>
<cfloop query="allLocCode">
<cfset thisLocationName = trim(allLocCode.trans_location) />
<cfquery name="allLocCodeForLocationQry" dbtype="query">
SELECT trans_location,count(*) AS locCntr FROM GetLocationInfo WHERE trans_location='#thisLocationName#' GROUP BY trans_location ORDER BY trans_location
</cfquery>
<cfoutput query="allLocCodeForLocationQry">
<tr>
<td><strong>#thisLocationName#</strong></td>
<td>#NumberFormat((allLocCodeForLocationQry.locCntr/columnSum) * 100, '9.99')#%</td>
<td>#allLocCodeForLocationQry.locCntr#</td>
</tr>
</cfoutput>
</cfloop>
<cfdump var="#allLocCodeForLocationQry.locCntr#">
<tr>
<td><strong>Total</strong></td>
<td></td>
<td><cfoutput>#columnSum#</cfoutput></td>
</tr>
</tbody>
</table>
Unsure of how I can get the sum of this: <td>#NumberFormat((allLocCodeForLocationQry.locCntr/columnSum) * 100, '9.99')#%</td>
You can simply push the calculated percentage to an array and from there you can get the sum like this:
<!--- Define Array -->
<cfset checkListPercentage = arrayNew(1)>
<cfoutput query="allLocCodeForLocationQry">
<cfset currentPercentage = allLocCodeForLocationQry.locCntr / columnSum * 100)>
<cfset arrayAppend(checkListPercentage, currentPercentage)>
<tr>
<td><strong>#thisLocationName#</strong></td>
<td>#numberFormat(currentPercentage, '9.99')#%</td>
<td>#allLocCodeForLocationQry.locCntr#</td>
</tr>
</cfoutput>
<!--- Get Total --->
<cfoutput>#arraySum(checkListPercentage)#</cfoutput>
I've posted a somewhat similar answer before to one of these questions. This'll get you where you need to be:
Every time you get a percentage, you should set it as a variable and add it to a list or array. As an example for this chunk of code:
<cfloop query="allLocCode">
<cfset thisLocationName = trim(allLocCode.trans_location) />
<cfquery name="allLocCodeForLocationQry" dbtype="query">
SELECT trans_location,count(*) AS locCntr FROM GetLocationInfo WHERE trans_location='#thisLocationName#' GROUP BY trans_location ORDER BY trans_location
</cfquery>
<cfset PercentageList = "">
<cfset thisPercentage = #NumberFormat((allLocCodeForLocationQry.locCntr/columnSum) * 100, '9.99')#>
<cfset PercentageList = ListAppend(PercentageList, thisPercentage, ',')>
<cfoutput query="allLocCodeForLocationQry">
<tr>
<td><strong>#thisLocationName#</strong></td>
<td>#thisPercentage#%</td>
<td>#allLocCodeForLocationQry.locCntr#</td>
</tr>
</cfoutput>
</cfloop>
At the end of all your calculations, you should have a list of percentages. You can include this function to add the list together.
<cfscript>
function listSum(listStr)
{
var delim = ",";
if(ArrayLen(Arguments) GTE 2)
delim = Arguments[2];
return ArraySum(ListToArray(listStr, delim));
}
</cfscript>
So your last row would be:
<tr>
<td><strong>Total</strong></td>
<td>#listSum(PercentageList)#%</td>
<td><cfoutput>#columnSum#</cfoutput></td>
</tr>
Worth mentioning: Previously, it was pointed out to me that using Arrays and then converting to a List at the end of your calculations results in better performance, so that's something to keep in mind.
ArraySum is the relevant function for this.
With all the loops and queries inside other loops and queries, I just figured creating a list was a little easier.
E - unexplained downvotes are not nice.

CF Getting the sum of a column on a database query

I am trying to calculate the total of a column using ColdFusion and MS Sql.
Will someone please tell me what I am overlooking? My total for the location total is not doing the sum of the column but for somereason just taking the last number in that column. Where am I going wrong?
<cfset result = {} />
<cftry>
<cfquery datasource="#application.dsn#" name="GetLocationInfo">
SELECT *
FROM cl_checklists
</cfquery>
<cfcatch type="any">
<cfset result.error = CFCATCH.message >
<cfset result.detail = CFCATCH.detail >
</cfcatch>
</cftry>
<table border="1" id="Checklist_Stats">
<thead>
<th><strong>Location</strong></th>
<th><strong>Percent of Total Checklists</strong></th>
<th><strong>Location Total</strong></th>
</thead>
<tbody>
<cfquery name="allLocCode" dbtype="query">
SELECT DISTINCT trans_location, COUNT(*) AS locationCount FROM GetLocationInfo GROUP BY trans_location ORDER BY trans_location
</cfquery>
<cfloop query="allLocCode">
<cfset thisLocationName = trim(allLocCode.trans_location) />
<cfquery name="allLocCodeForLocationQry" dbtype="query">
SELECT trans_location,count(trans_location) AS locCntr FROM GetLocationInfo WHERE trans_location='#thisLocationName#' GROUP BY trans_location ORDER BY trans_location
</cfquery>
<cfset columnSum = ArraySum(allLocCodeForLocationQry['locCntr'])>
<cfoutput query="allLocCodeForLocationQry">
<tr>
<td><strong>#thisLocationName#</strong></td>
<td>#NumberFormat((allLocCodeForLocationQry.locCntr/allLocCode.locationCount) * 100, '9.99')#%</td>
<td>#allLocCodeForLocationQry.locCntr#</td>
</tr>
</cfoutput>
</cfloop>
<tr>
<td><strong>Total</strong></td>
<td></td>
<td><cfoutput>#numberFormat(columnSum)#</cfoutput></td>
</tr>
</tbody>
<!--- Total of All Sum of each column --->
</table>
Your columnSum variable is inside your cfloop. Put the <cfset columnSum = ArraySum(allLocCodeForLocationQry['locCntr'])> line outside of the cfloop (either before or after), and you should get your grand total of 334.
Try this.
Each time you loop through the query, append a value (the count of locations) to a list.
Something like this:
<cfset myList = "">
<cfloop query="allLocCode">
<cfset myList = ListAppend(myList, locationCount, ',')>
<!---your other logic--->
</cfloop>
At the end of your loop you should have a list of numbers as long as your query's recordcount.
You can add up all those numbers using this old function I found on CFLib.
<cfscript>
function listSum(listStr)
{
var delim = ",";
if(ArrayLen(Arguments) GTE 2)
delim = Arguments[2];
return ArraySum(ListToArray(listStr, delim));
}
</cfscript>
So, for example, if your final list was called myList and had values such as 14, 100, 7 - you would write out:
<cfoutput>#listSum(myList)#</cfoutput>
And get your final answer of 121.
Since this is sql server, why not take advantage of its ability to use the with keyword? The general idea is this:
with totalRecords as
(select count(*) records
from etc),
groupedRecords as
(select someField, count(*) recordsForField
from etc
group by someField)
select whatevever
, (groupedRecords.recordsForField / totalRecords.records) * 100 percentage
from someTables
join groupedRecords on groupedRecords.someField = someTable.someField
where totalRecords.records > 0
Then you simply output your query results.

ColdFusion cfloop skip row or change loop endRow

I am trying to display 2 images, and skip one if it matches the following criteria (<cfif myDir.name eq property_mainimage> which works fine, and then continue onto the next image and display the next image until I have a total of 2 images. But when the criteria image is say in row 5, the loop displays 3 images, when the criteria image is say row 1, it displays 2 images.
There doesn't seem to be a skip row in cfloop?
I have tried <cfif counter gt 3 > <cfabort> which works but it displays the 3 images still of the criteria image is in a row greater than 3. Below is what i'm working with...
<cfdirectory directory="C:\Domains\domain.com\wwwroot\uploads\images\#property_ID#\" filter="*.jpg" name="myDir" type="file" sort="datelastmodified">
<ul>
<cfset counter = 0>
<cfset endrowvalue = 3 >
<cfloop query="myDir" endRow="#endrowvalue#">
<cfset counter = counter +1 >
<li>
<cfif right(myDir.name,4) is ".jpg">
<cfif fileexists("C:\Domains\ domain.com\wwwroot\uploads\ images\#property_ID#\#left(mydir.name,len(myDir.name)-4)#.jpg")>
<cfif myDir.name eq property_mainimage>
DO NOT SHOW THIS IMAGE
<cfelse>
<cfset endrowvalue = 1 >
<cfset myDir.endRow = 1 >
test #endrowvalue#
test #counter# <img src="#request.root#uploads/images/#property_ID#/#myDir.name#" border="0" width="230px" style="margin-bottom:15px;" />
</cfif>
</cfif>
</cfif>
</li>
</cfloop>
</ul>
any help would be most appreciated.
I would use a counter to count when you show the image. Once you get to 2 images displayed break out of the loop.
<cfdirectory directory="C:\Domains\domain.com\wwwroot\uploads\images\#property_ID#\" filter="*.jpg" name="myDir" type="file" sort="datelastmodified">
<ul>
<cfset counter = 1>
<cfloop query="myDir">
<li>
<cfif right(myDir.name,4) is ".jpg">
<cfif fileexists("C:\Domains\ domain.com\wwwroot\uploads\ images\#property_ID#\#left(mydir.name,len(myDir.name)-4)#.jpg")>
<cfif myDir.name eq property_mainimage>
DO NOT SHOW THIS IMAGE
<cfelse>
<!--- image displayed increment coutner --->
<cfset counter++>
<img src="#request.root#uploads/images/#property_ID#/#myDir.name#" border="0" width="230px" style="margin-bottom:15px;" />
</cfif>
</cfif>
</cfif>
<cfif counter EQ 2>
<cfbreak>
</cfif>
</li>
</cfloop>
</ul>
This is a formatted comment. Your code has this:
<cfset endrowvalue = 3 >
<cfloop query="myDir" endRow="#endrowvalue#">
<cfif myDir.name eq property_mainimage>
DO NOT SHOW THIS IMAGE
<cfelse>
<cfset endrowvalue = 1 >
You would have to test it to be sure, but I suspect that the endRow attribute of your cfloop tag will continue to be 3, even if you change the value of the endrowvalue variable to 1.
This might not be the cause of your current problem, but, it my suspicians are correct, you will either have a problem elsewhere or you are running a pointless command.

Including or excluding range attribute in dynamically generate form field

I am using a query to dynamically create form fields, not all fields use the range attribute.
When using the cfif statement to include or exclude the range attribute I get an error:
See code below:
<cfoutput>
<input type="hidden" name="question_ids" id="question_ids" value="#valueList(rsQuestions.question_id)#">
</cfoutput>
<cfoutput query="rsQuestions" group="modid">
<table border="1" cellpadding="4" cellspacing="4" bgcolor="##0E777A" >
<tr>
<td colspan="2"><span class="style1">#rsQuestions.ModName#</span></td>
</tr>
<cfoutput>
<tr>
<td width="700" bgcolor="##FFFFFF">#rsQuestions.question#</td>
<td width="200" bgcolor="##FFFFFF">
<cfif rsQuestions.question_type_id eq 1>
<cfinput type="text" name="answer_#rsQuestions.question_id#"
message="#rsQuestions.Message#"
tooltip="#rsQuestions.Tooltip#"
validate="#rsQuestions.Validate#"
<cfif #rsQuestions.Range# neq "">
range = "#rsQuestions.Range#"
</cfif>
required="#rsQuestions.mandatory#"
size="#rsQuestions.Size#">
<cfelseif rsQuestions.question_type_id eq 2>
<cfquery name="rsOptions" datasource="dsTest">
SELECT option_id, [option], question_id
FROM questionnaire_question_options
WHERE (question_id = #rsQuestions.question_id#)
</cfquery>
<cfselect enabled="yes"
name="answer_#rsQuestions.question_id#"
multiple="no"
query="rsOptions"
value="option"
display="option">
</cfselect>
</cfif>
</td>
</tr>
</cfoutput>
</table>
</cfoutput>
How can I structure the above statement to include or exclude the 'range' attribute?
As user8675309 (Jenny?) mentioned, you cannot nest <cfif> tags inside another CF tag. So you need to separate those statements out. Here is one way you could do that:
....
<cfif rsQuestions.question_type_id eq 1>
<cfif rsQuestions.Range neq "">
<cfinput type="text" name="answer_#rsQuestions.question_id#"
message="#rsQuestions.Message#"
tooltip="#rsQuestions.Tooltip#"
validate="#rsQuestions.Validate#"
range="#rsQuestions.Range#"
required="#rsQuestions.mandatory#"
size="#rsQuestions.Size#">
<cfelse>
<cfinput type="text" name="answer_#rsQuestions.question_id#"
message="#rsQuestions.Message#"
tooltip="#rsQuestions.Tooltip#"
validate="#rsQuestions.Validate#"
required="#rsQuestions.mandatory#"
size="#rsQuestions.Size#">
</cfif>
<cfelseif rsQuestions.question_type_id eq 2>
....
As mentioned, you can't nest a cfif (or any CF tag) inside another CF tag.
One thing you can do if you really need dynamic attributes is to use the "attributeCollection" attribute.
(ColdFusion 8 or higher.)
Something like:
<cfset inputAttr=structNew()>
<cfset inputAttr.type="text">
<cfset inputAttr.name="answer_#rsQuestions.question_id#">
<cfset inputAttr.message="#rsQuestions.Message#">
<cfset inputAttr.tooltip="#rsQuestions.Tooltip#">
<cfset inputAttr.validate="#rsQuestions.Validate#">
<cfif rsQuestions.Range neq "">
<cfset inputAttr.range = "#rsQuestions.Range#">
</cfif>
<cfset inputAttr.required="#rsQuestions.mandatory#">
<cfset inputAttr.size="#rsQuestions.Size#">
<cfinput attributecollection="#inputAttr#">

how to loop through Query Columns in ColdFusion

I have a query in a my CFC. The function contains a simple query as such.
<cfquery name="qrySE" datasource=#mydatasource#>
SELECT
NAMES,SALARY
FROM tblTest
</cfquery>
I want to display my resultset as such (horizontally):
NAME1 NAME2 NAME3 NAME4
10 20 45 62
Is there a way to loop through the columns of my query and create a virtual query for this purpose?
If anyone has done this, please let me know.
Just wanted to add Al Everett's solution returns the columns back in alphabetical order. If you would like to get the column names back in the same order as the query you can use:
ArrayToList( qrySE.getColumnNames() )
which I found here: http://www.richarddavies.us/archives/2009/07/cf_columnlist.php
you can use this to create a function to output queries to a table like this:
<cffunction name="displayQueryAsTable" output="true">
<cfargument name="rawQueryObject" type="query" required="true">
<table >
<tr>
<cfloop list="#ArrayToList(rawQueryObject.getColumnNames())#" index="col" >
<th>#col#</th>
</cfloop>
</tr>
<cfloop query="rawQueryObject">
<tr>
<cfloop list="#ArrayToList(rawQueryObject.getColumnNames())#" index="col">
<td>#rawQueryObject[col][currentrow]#</td>
</cfloop>
</tr>
</cfloop>
</table>
</cffunction>
You could use the built-in query.columnList that is returned with each query. (It's metadata of the query, like recordCount.)
You could do something like this:
<table>
<cfloop list="#qrySE.columnList#" index="col">
<tr>
<cfloop query="qrySE">
<td>#qrySE[col][currentRow]#</td>
</cfloop>
</tr>
</cfloop>
</table>
Not tested, but that should give you the idea.