How can I access the query for my cfoutput dynamically, based on a query name variable? - dynamic

I have a struct that contains 2 queries. I have a variable with the "key" of one of the queries, and I want to output the query dynamically using that variable. My basic code:
<cfquery name="myQueries.names" ... >...</cfquery>
<cfquery name="myQueries.places" ... >...</cfquery>
<cfset queryName = "places" />
<cfoutput query="myQueries[queryName]">
...
</cfoutput>
This gives me the error Attribute validation error for tag cfoutput.
The cfoutput "query" attribute doesn't seem to support bracket notation. How can I access the query from the cfoutput?

The query attribute of cfoutput requires a valid variable name, so you can set an intermediary value and use that to reference your query
<cfset realQuery = myQueries[queryName]>
<cfoutput query="realQuery">
...
</cfoutput>

Related

how to get a value out of a ColdFusion struct object

I am creating a pdf document (via ColdFusion), and rendering the pdf in a browser. The pdf form is already created and I am prefilling and populating the fields.
So what I am doing is dumping the variables out from the pdf to use as the name in a cfpdfformparam. (to get the variables) Then what I am doing is creating where owner email is the name of the variable from the pdf and then for the value I am assigning the session variable from another form. So that what they have entered prefills in the form they need to fill out. So really name decides the location on the pdf and value is the session variable of what was entered on the other form.
The issue I am having is that the variables that were already created, a few of them have structs inside of the variables so I am not sure how to call them in (name portion) in order to prefill and populate the information.
For example how would I prefill in the information for FEID/DL/DMVacct and for FL reg when they contain a struct within the variable?:
like this?: <cfpdfformparam
name="FEID/DL/DMVacct##"
value="#session.checkout.info.driverlicense_1#">
<cfpdfform action="read" source="82040y.pdf" result="data" />
<cfdump var="#data#" />
I am pre-populating the pdf form fields (via ColdFusion session variables), and then rendering the pdf using the following markup:
<cfpdfform source="82040.pdf" action="populate">
<cfpdfformparam name="org" value="">
</cfpdfform>
Any help would be greatly appreciated!
You can access variables embedded inside a struct like this:
<!--- using dot notation --->
<cfif StructKeyExists(myStruct, "myKey")>
<cfoutput> #mystruct.myKey#</cfoutput><br>
</cfif>
<!--- or using access notation --->
<cfif StructKeyExists(myStruct, LastName)>
<cfoutput>#LastName#: #mystruct[LastName]#</cfoutput><br>
</cfif>
You can use IsDefined to see if a value exists:
IsDefined("structure_name.key")>
However, if the key is dynamic, or contains special characters, you must use the StructKeyExists function.
NOTE: You must be careful about your variable names in ColdFusion. Some of the names assigned to your struct values would be considered invalid if used as variable names. So if your struct names contain invalid characters, you will need to access them via access-notation in order to retrieve them:
<!--- use access-notation for value names with special chars --->
data["FEID/DL/DMVacct"]["#"]
Otherwise, you will have runtime errors if you attempt dot-notation:
<!--- Invalid markup! Don't do this! --->
#data.FEID/DL/DMVacct.##
So here are some examples of how you could access your data:
<!--- Output the value --->
<cfoutput> #data["FEID/DL/DMVacct"]["#"]#</cfoutput><br>
<!--- Storing the value in a variable named 'myVar' --->
<cfset myVar = #data["FEID/DL/DMVacct"]["#"]# />
<cfoutput>#myVar#</cfoutput>
If your struct names follow ColdFusion's variable naming rules, then you can also access your data with dot-notation, notice I changed the value names FEID/DL/DMVacct and # to valid variable names: FEID_DL_DMVacct and num:
<!--- Output the value via dot-notation --->
<cfoutput> #data.FEID_DL_DMVacct.num#</cfoutput><br>
<!--- Storing the value in a variable named 'myVar' --->
<cfset myVar = #data.FEID_DL_DMVacct.num# />
<cfoutput>#myVar#</cfoutput>
Hope this helps!
structName['FEID/DL/DMVacct']['##'] = variable
You need the double # to escape them and produce one singular #

ColdFusion Query Output Displaying Variable Name Instead Of Field Value

I'm an "old dog" and largely self-taught on this stuff and can usually make things work (primative and convoluted as it might be), but this is the first thing that has me really stymied.
I didn't want to burden everyone with a lot of stuff to try to explain, but, here is perhaps a better explanation and example:
(#Leigh - and thank you for your time and help!) - The query is dynamic because what I desire to have is a single "universal" page combination (form page plus accompanying action page) that is used to edit multiple different (but fairly similar) record sets (so that I don't have to write a whole bunch of individual form/action page pairs).
When this "universal" "change" form page is invoked, it is passed the "ID" variable for the particular record to be edited, along with a "listID" variable unique to the particular record set containing the record to be edited.
Using the "URL.listID", the form page then looks at a pre-defined included list of record set variables (datasource, query table, field for column 1, field for column 2, etc.) pertaining to the value of the "listID" and sets (using ) the dynamic variables. Example - if "listID" is "5", which has only one column:
<cfif #URL.listID# EQ 5>
<cfset page_title = 'Change Member Role Picklist'>
<cfset datasource = '#Session.db_docs#'>
<cfset query_tbl = 'tblMemberRole'>
<cfset columns = 1>
<cfset column1_label = 'Member Role'>
<cfset column1_field = "role">
<cfset column1_input_type = "text">
<cfset column1_input_size = "100">
<cfset column1_input_maxlength = "100">
</cfif>
The query uses those variables ("ID" plus the others it got from the above list) to retrieve the individual record to be edited, and populate the "change" form.
Run query:
<cfquery name="cfqGetItem" datasource="#datasource#">
SELECT *
FROM #query_tbl#
WHERE ID = <cfqueryparam value="#URL.ID#" cfsqltype="cf_sql_integer">
</cfquery>
My "change" form (abbreviated here without table HTML) to be populated would be:
<form name="form_item_chg" action="chg_item2.cfm" method="post" enctype="multipart/form-data">
<input type="text" name="#column1_field#" maxlength="#column1_input_maxlength#" size="#column1_input_size#" value="#cfqGetItem[column1_field][currentRow]#">
<input type="Submit" value="Post Changes">
</form>
However, instead of the "change" form being populated with the VALUE for field "role", it instead is trying to use the variable name "column1_field", which it says is (true, of course) undefined in the query.
When I tried "#cfqGetItem[column1_field][currentRow]#", it says "Variable currentrow is not defined".
When I tried "#cfqGetItem.column1_field#", it says "Element column1_field is not defined in query cfqGetItem".
I apologize in advance for not knowing/using all the correct terminology, and hope I am explaining this reasonably clearly. I suspect I will have to revert to writing individual form-page/action-page pairs. Thank you to all for your time and help!
ORIGINAL POST:
I'm not highly technical, and this is probably something simple, but here is
my dilemma, where I am attempting to retrieve a single record using a variable name in the query.
First, I define some variables:
<cfset ID = #Form.ID#<!--- the single record I want to retrieve, passed from a form --->
<cfset datasource = 'MyDatabase'>
<cfset query_tbl = 'MyDatabaseTable'>
<cfset field1 = 'actual_fieldname1'><!--- field in MyDatabaseTable --->
<cfset field2 = 'actual_fieldname2'><!--- field in MyDatabaseTable --->
ETC.
Then, to retrieve this single record, I run a query using those variables:
<cfquery name="cfqGetItem" datasource="#datasource#">
SELECT *
FROM #query_tbl#
WHERE ID = #ID#
</cfquery>
Then, I attempt to display the query output:
EITHER AS
<cfoutput>
<p>#cfqGetItem.field1#
<p>#cfqGetItem.field2#
</cfoutput>
OR, AS
<cfoutput>
<p>#cfqGetItem[field1][currentRow]#
<p>#cfqGetItem[field2][currentRow]#
</cfoutput>
In each case, I get a similar CF error message: "Element field1 is not defined in query cfqGetItem", or "Variable currentrow is not defined".
How can I get the query output to generate the actual values for the record instead of the variable names?
Thank you very much for any help!
If you change this:
<cfoutput>
<p>#cfqGetItem[field1][currentRow]#
<p>#cfqGetItem[field2][currentRow]#
</cfoutput>
to this:
<cfoutput>
<cfloop query="cfqGetItem">
<p>#cfqGetItem[field1][currentRow]#
<p>#cfqGetItem[field2][currentRow]#
</cfloop>
</cfoutput>
You should be ok. However, this is the simplest way
<cfoutput query="cfqGetItem">
<p>#actual_fieldname1#
<p>#actual_fieldname1#
</cfoutput>
Setting the table and field names to variables complicates matters. Unless they really can vary, don't do it. Also, the cfqueryparam tag is your friend. Use it in places like this:
where id = <cfqueryparam
cfsqltype = "cf_sql_integer"
value = "#id#">
You can try out like this also:
<cfquery
name="GetParks" datasource="cfdocexamples"
>
SELECT PARKNAME, REGION, STATE
FROM Parks
ORDER BY ParkName, State
</cfquery>
<cfoutput>
<p>#GetParks.PARKNAME#
<p>#GetParks.REGION#
</cfoutput>
<cfoutput >
#GetParks['state'][GetParks.RecordCount]#
</cfoutput>
<cfoutput >
#GetParks['state'][2]#
</cfoutput>

Access resultset value of cfprocresult name in cfif

I am new to ColdFusion and want to rewrite my project from ASP.NET to learn ColdFusion step by step.
My SQL Server stored procedure for authentication (ASP.NET) looks like this:
CREATE PROCEDURE sp_auth
#suser VARCHAR(20),
#spswd VARCHAR(20)
AS
SELECT COUNT(*) FROM Users.SUsers WHERE suname=#suser AND supasswd=#spswd AND off_bit=0
GO
Application.cfc snippet.
<cfstoredproc procedure="sp_auth" datasource="cftraderelay">
<cfprocparam value="#cflogin.name#" cfsqltype="CF_SQL_VARCHAR" maxlength="20" type="in">
<cfprocparam value="#cflogin.password#" cfsqltype="CF_SQL_VARCHAR" maxlength="20" type="in">
<cfprocresult name="auth_pass" maxrows="1">
</cfstoredproc>
<cfif auth_pass GTE 1>
<cfloginuser name="#cflogin.name#" password = "#cflogin.password#" roles="#roles#">
<cfelse>
<cfoutput>
<h2>Your login information is not valid.<br> Please Try again</h2>
</cfoutput>
<cfinclude template="login.cfm">
<cfabort>
</cfif>
What is right form of 'cfif auth_pass GTE 1' logic? How to access the value of 'auth_pass'.
Cos I get "Complex object types cannot be converted to simple values" error by far.
Am I strictly supposed to use out type of cfprocparam in this case, not cfprocresult (modify SQL query for the OUTPUT variable)?
Can I access cfprocresult value right in the cfif statement?
auth_pass contains a recordset, not a number, so you cannot compare it to 1. You perhaps want auth_pass.recordCount?
The best tool for examining the contents of a variable is <cfdump>. That and familiairising yourself with the docs for the code you're using, eg: <cfprocresult>, <cfstoredproc>, <cfquery> (the latter for details on query objects) if you run into problems and can't guess the solution.

ColdFusion - Nested Variable (dynamic variable read) [duplicate]

This question already has answers here:
Coldfusion - variable field name when looping through database query results
(2 answers)
Closed 9 years ago.
Edit: The QUESTION is a duplicate, but the ANSWER is not!
I have the following code:
<cfquery name="contact" datasource="thesource">
SELECT * FROM #table# WHERE foo = '#bar#'
</cfquery>
and then later on (this is the problem part):
<cfloop from="0" to="9" index="i">
<cfset thisvar = Evaluate("contact.check" & i) />
<cfoutput>
#thisvar#
</cfoutput>
</cfloop>
Upon execution, it throws a nice big "Variable contact.check0 is Undefined". However, #contact.check0# will output just fine if hardcoded.
Any ideas on how to fix this?
Note:
I have seen Coldfusion - variable field name when looping through database query results, and although the problem seems to be exactly the same, the solutions do not work. As per the comments, I am also getting a "cannot be converted to a number" error. I notice Tomalak mentions "a little catch", but never says what it is. In the article he links to, I have tried every syntactically equivalent form, and it all throws an error...either cannot convert to a number or is not defined.
Also, I'm aware Evaluate() has overhead and "should not be used". I'll take any solution that works, whether it has Evaluate in it or not.
This is on ColdFusion 9.
Thank you
Edit: while a similar question already had an answer, this question had a different cause. See accepted answer below.
First of all, standard blub about escaping inputs. cfqueryparam exists for a reason. That aside you can do this without evaluate. Give this a try instead, including a check to make sure there is actually a result
<!--- make sure that there is actually a result --->
<cfif contact.RecordCount EQ 0>
NO RESULT
<cfelse>
<cfloop from="0" to="9" index="i">
<!--- assumes that you want row 1 --->
<!--- check.CurrentRow could also be used instead of 1 --->
<cfset thisvar = contact['check'&i][1] />
<cfoutput>
#thisvar#
</cfoutput>
</cfloop>
</cfif>
I suspect that it is attempting to Evaluate the column without specification of the row number, while when hard-coding it you'll find it uses the current row.
edit as Dan Bracuk pointed out this is an exact duplicate of the question you linked in your question, Coldfusion - variable field name when looping through database query results
This is ridiculous and absurd. Working code (moved things around a bit):
<cfoutput>
<cfloop from="0" to="9" index="i">
<cfset thisvar = contact["check"&i][1] />
#thisvar#
</cfloop>
</cfoutput>
NOT working code:
<cfoutput query="contact"> <!--- this line here --->
<cfloop from="0" to="9" index="i">
<cfset thisvar = contact["check"&i][1] />
#thisvar#
</cfloop>
</cfoutput>
Someone else had put cfoutput tags around the whole page. While this normally wouldn't be a problem, they ALSO declared the query attribute. This somehow overwrote the original query from the db. Calling contact.check0 worked just fine, but building the variable name dynamically, I think, was attempting to reference the cfoutput's query attribute.
Thanks to Peter Boughton for the suggestion to extract the problem code...which led me to this realization, and Simon for posting the syntactically correct code. Points go to them.

Double evaluation - How do I access my query column based on a variable that holds the column name?

I have a query and a list of field/column names. I want to do a sort of double loop - loop through each record in the query, and then loop through the list of field/column names and output each corresponding field. The loops should be something like this:
<table>
<cfoutput query="myQuery">
<tr>
<cfloop list="#cols#" index="col">
<td>?</td>
</cfloop>
</tr>
</cfoutput>
</table>
The problem is what to put where the question mark is... I've tried #myquery[col]#, but this didn't work. I need to get the variable indicated by the string name in the variable col... And obviously, #col# will just return the column name. I need to figure out some way to double-evaluate the string... something like ##col##, which of course won't work either. How can I accomplish this?
When referencing column names as a structure, you need to also tell the query which row you want to get. You should also make sure that you check that the column name exists if you didn't get the cols variable via myQuery.ColumnList.
Use the following code to dynamically reference each column in your loop:
<table>
<cfoutput query="myQuery">
<tr>
<cfloop list="#cols#" index="col">
<td>#myQuery[col][CurrentRow]#</td>
</cfloop>
</tr>
</cfoutput>
</table>
You can still use Sergii's approach with your own columnlist:
<cfloop list="#cols#" index="col">
<cfif StructKeyExists(myQuery, col)>
<td>#col# = #myQuery[col][myQuery.CurrentRow]#</td>
</cfif>
</cfloop>
Got it!! :)
#evaluate(evaluate("col"))#