Where to put a cfquery in a Coldfusion Form - coldfusion

I have a cfquery that is using some of FORM fields in the WHERE clause. My first problem is that every time I access my webpage the cfquery code appears on the top of the page. Where should I put the query within the .cfm form and access some of the fields within the form? My second problem is I'm not sure that the WHERE clause is recognizing the values for the fields. Can you help me please?
Here is the way my code is set up:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
function addRow() {
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
var iteration = lastRow - 3;
var row = tbl.insertRow(lastRow);
........... etcetra.......
}
</script>
</head>
<body lang=EN-US style='tab-interval:.5in'>
<div class=Section1>
<cfparam name="awardTotals" default="0" />
<cfparam name="search_award.GrandTotal" default="0" />
<cfif isDefined("form.Finalize")>
<cfquery name="search_award" datasource="Test">
SELECT g.Code1 + g.Code2 + g.Code3 + g.Code4 AS GrandTotal
FROM Codes g
WHERE g.CodeNumber = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.CodeNum#">
AND g.TestYear = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.TestYear#">
AND g.SelType = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.SelType#">
AND g.Jurisdiction = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.SelJuris#">
</cfquery>
<cfif not search_award.GrandTotal is FundingTotals>
<script type="text/javascript">
alert('The totals do not match.');
return false;
</script>
<cfelse>
<script type="text/javascript">
alert('The totals match.');
return true;
</script>
</cfif>
</cfif>
<p class=MsoNormal align=center style='text-align:center'><
<cfoutput>
<form name="thisform" action="FormData.cfm" method="post">
<p class=MsoNormal align=left style='text-align:left'>
<input type="hidden" id="totalFields" name="totalFields" value="0">
<input type="text" id="awardTotals" name="#search_award.GrantTotal#" value="0">
<table width="1177" border="1" id="tblSample">
<tr style='mso-yfti-irow:0;mso-yfti-firstrow:yes'>
<th height="10"bgcolor="##cccccc" colspan="10"><h3>Jurisdiction:
<select name="SelJuris" id="SelJuris">
<option value = "0">---Jurisdictions---</option>
<option value = "1">Allegany County</option>
<option value = "2">Anne Arundel County</option>
<option value = "3">Baltimore County</option>
<option value = "4">Calvert County</option>
<option value = "5">Caroline County</option>
</select>
<input name="CodeNum" id="CodeNum" type="text" size="20">
<input name="TestYear" id="TestYear" type="text" size="20">
<input name="SelType" id="SelType" type="text" size="20">
</th>
</tr>
</table>
<input type="Submit" name="Submit Form" value="Submit Form" onClick="">
<input type="Button" name="Finalize" value="Finalize" onClick="">
</form>
</body>
</cfoutput>
</html>
(Update from comments)
Right now I'm getting a message that Element CODENUM is undefined in FORM

You want this sort of logic. If the form has been submitted, do something with it. In your case, it would be like this:
<cfif structkeyexists(form, "codenum")>
query, process, display, etc
<cfif>
rest of page
Also, you want to use query parameters for a variety of reasons. So this:
g.CodeNumber = '#form.CodeNum#'
becomes this:
g.CodeNumber = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.CodeNum#">
unless it's a number in which case you change the datatype.

You need add a condition around your cfquery. Also update the name of your submit button without spaces
<input type="Submit" name="SubmitForm" value="Submit Form" onClick="">
<cfif isDefined("form.SubmitForm")>
<cfquery name="search_award" datasource="TrenaTest">
SELECT g.Code1 + g.Code2 + g.Code3 + g.Code4 AS GrandTotal
FROM Codes g
WHERE g.CodeNumber = '#form.CodeNum#'
AND g.TestYear = '#form.TestYear#'
AND g.SelType = '#form.SelType#'
AND g.JurisdictionID = '#form.SelJuris#'
</cfquery>
</cfif>

Please note that in all the examples, a standard html form tag is being used, but the condition for the query is defined in the Coldfusion form scope. I believe you would need to convert the <form> to <cfform> and <input> to <cfinput> like:
...........
<cfinput type="Submit" name="SubmitForm" value="Submit Form" onClick="">
</cfform>
<cfif isdefined('form.submit')>
.............

Related

ColdFusion Options removed after selecting option

I'm having trouble with my ColdFusion code. I'm trying to create a simple HTML select form using cfloop to populate the options. it works, and when you select an option, it pulls that option from the db. but once you do that, the only option available is the option previously selected. What am I doing wrong?
<!--- Query the DataBase --->
<cfparam name="url.colors" default="">
<cfif structKeyExists(form, "colordb")>
<cfset url.colordb = form.colordb>
</cfif>
<cfquery datasource="bentest" name="colors">
SELECT *
FROM color_codes
<cfif structKeyExists(url,"colordb") and isNumeric(url.colordb)>
WHERE id=#url.colordb#
</cfif>
</cfquery>
<!--- Add Selector for user to select a color --->
<div class="selector">
<cfoutput>
<form action="?contentId=colorPickdb" name="clr" method="post" class="clr">
<select class="clr" name="colordb" onChange="submit();">
<option selected>Select A Color!</option>
<cfloop query="colors">
<option value="#colors.id#">#colors.color#</option>
</cfloop>
</select>
</form>
</cfoutput>
</div>
<div class="dump">
<!--- Output results of Query --->
<p><cfif structKeyExists(form, "colordb")>
<cfoutput query="colors">
#colors.color# <br>
#colors.hexvalue# <br><br>
</cfoutput>
</cfif>
<br>
</p>
</div>
You can use query of query here.
<!--- Query the DataBase --->
<cfparam name="url.colors" default="">
<cfquery datasource="bentest" name="colors">
SELECT *
FROM color_codes
</cfquery>
<!--- Add Selector for user to select a color --->
<div class="selector">
<cfoutput>
<form action="?contentId=colorPickdb" name="clr" method="post" class="clr">
<select class="clr" name="colordb" onChange="submit();">
<option selected>Select A Color!</option>
<cfloop query="colors">
<option value="#colors.id#">#colors.color#</option>
</cfloop>
</select>
</form>
</cfoutput>
</div>
<div class="dump">
<!--- Output results of Query --->
<p>
<cfif structKeyExists(form, "colordb")>
<cfquery dbtype="query" name="colorSelected">
SELECT *
FROM colors
WHERE id=#form.colordb#
</cfquery>
<cfoutput query="colorSelected">
#colorSelected.color# <br>
#colorSelected.hexvalue# <br><br>
</cfoutput>
</cfif>
<br>
</p>
</div>

Form counting every record when clicking submit?

I have a form that im outputting results of comments, it can more than one.
I can aprrove these comments all at once, but what I'm trying to do is make it
with the option to submit 1 comment at a time or all comments at a time.
The form at first I wrote it to work on 'submit all', so now with adding a submit
per comment also, I get some errors.
I get because every time I submit a comment (1 comment) its still looking for all the other comments
which I did not submit.
What I think is doing since txtTotalRecords= Mush2.Recordcount, it trying to find the
other records which weren't submitted.
I just can't figure out how I can change this to make it work.
Doing a cfdump on the form i get, meaning there are 11 comments to submit.
How would I be able to change RecordCount to take in every record by itself?
<cfparam name="FormSubmit" type="string" default="FormNotSubmitted">
<cfif isDefined("form.submit")><cfset FormSubmit = "FormSubmitted"></cfif>
<cfif isDefined("form.submit1")><cfset FormSubmit = "FormSubmitted1"></cfif>
<!--- Begin Content ================================================== --->
<cfif FormSubmit eq "FormNotSubmitted" || FormSubmit eq "FormNotSubmitted1" >
<form method="post" action="cse_execoffice_pending.cfm" name="review_comments">
<cfoutput>
<input type="hidden" name="txtApprovedBy" value="#GetCurrentUser.emp_id#">
<!-- count the records that come in from the pending -->
</cfoutput>
<cfoutput query="Mush3">
<form method="post" action="cse_execoffice_pending.cfm" name="review_onecomment">
<input type="hidden" name="txtTotalRecords" value="#Mush2.Recordcount#">
<hr>
<div class="comments_approvaldecision">
<p>
<CFDUMP VAR=#response_id#>
<input type="hidden" name="txtResponseID#mush2.CurrentRow#" value="#response_id#">
<input type="radio" name="execoffice_status#mush2.CurrentRow#" id="approve#CurrentRow#" value="1" checked="checked"> <label for="approve#CurrentRow#">Approve</label><br>
<input type="radio" name="execoffice_status#mush2.CurrentRow#" id="deny#CurrentRow#" value="2"> <label for="deny#CurrentRow#">Deny</label>
</p>
<p> </p>
<p>
<input type="radio" name="star#mush2.CurrentRow#" id="givestar#mush2.CurrentRow#" value="0" checked="checked"> <label for="givestar#CurrentRow#"></i> Give Star!</label><br>
<input type="radio" name="star#mush2.CurrentRow#" id="denystar#mush2.CurrentRow#" value="1"> <label for="denystar#CurrentRow#"></i> No Star</label>
</p>
</div>
</div>
<input type="submit" name="Submit1" value="Submit">
</form>
</cfoutput>
<p><input type="submit" name="Submit" value="Submit"></p>
</form>
</cfif>
<cfdump var="#form#">
<cfif FormSubmit eq "FormSubmitted" || FormSubmit eq "FormSubmitted1">
<!--- Get Form Values --->
<cfloop from="1" to="#txtTotalRecords#" index="j">
<h2>test</h2>
<cfset response_id[j] = #Trim(form["txtResponseID" & j])#>
<cfset execoffice_status[j] = #Trim(form["execoffice_status" & j])#>
<cfset star[j] = #Trim(form["star" & j])#>
<cfset commentpositive[j] = #Trim(form["txtCommentPositive" & j])#>
<cfset commentnegative[j] = #Trim(form["txtCommentNegative" & j])#>
<cfset commentpositivereReplace[j] = reReplace(commentpositive[j], '\n', '<br>', 'ALL')>
<cfset commentnegativereReplace[j] = reReplace(commentnegative[j], '\n', '<br>', 'ALL')>
</cfloop>
......... more code...
I believe the code you are getting errors on is not in your sample code listed on this page.
I'm assuming you are doing a to/from loop based upon form.txtTotalRecords.
What you'll want to do is loop over your form items looking for a specific partial form name.
something like this:
<cfloop list="form.fieldnames" index="i">
<cfif left(i,13) IS "txtResponseID">
<cfset thisID = replaceNoCase(i,"txtResponseID","")>
<cfquery>
UPDATE myTable
SET approve = <cfqueryparam value="#form["execoffice_status" & thisID]#">
WHERE ID = <cfqueryparam value="#thisID">
</cfquery>
</cfif>
</cfloop>

File Upload is executing multiple times

I am trying to create a form where by the user selects a location where they then upload a document using CFFILE ACTION ="UPLOAD". I am not great at this so any help you could provide would be greatly appreciated.
Below is my code. Essentially, there is a dropdown list of folder locations. The user first selects one of the locations. Then clicks 'browse' to choose a file. Finally they click submit and the file uploads.
The code that is #dir# is the folder location that is linked to each of the location names. What is happening at the moment is that the document gets uploaded successfully... but it is uploading to all the folder locations instead of the one that is selected from the dropdown. Here is my code:
docuploads.cfm
<cfquery name="getLocation">
SELECT *
FROM Locations
ORDER BY FolderName
</cfquery>
<form action="docuploads.cfm" method="POST" enctype="multipart/form-data" name="upload_form" id="upload_form">
<select name="folderID">
<option value="">--- Select Folder ---</option>
<cfoutput query="getLocation">
<option value="#FolderName#"">#FolderName#</option>
</cfoutput>
</select>
<cfoutput query="getLocation">
<CFIF IsDefined("form.upload_now")>
<CFIF structKeyExists(form, "ul_path") and len(form["ul_path"])>
<CFFILE ACTION="UPLOAD" FILEFIELD="ul_path"
DESTINATION="C:\Documents\#dir#\"
NAMECONFLICT="OverWrite">
<CFSET ClientFilePath = "#clientDirectory#\#clientFile#">
</CFIF>
</CFIF>
</CFOUTPUT>
<br /><br />
Click on the Browse button to select the file to Upload:<br>
<input type="file" name="ul_path" id="ul_path" style="height: 22px;width: 350px;" value=""><br><br>
<input type="submit" name="upload_now" id="upload_now" value="Submit" style="height: 22px;">
<input type="button" name="clear" value="Clear" style="height: 22px;">
<br /><br /><br />
</form>
I hope this makes some sense - can anyone shed any light on getting this to work?
I am assuming that you didnt post the complete code because your #clientDirectory#/#clientFile# don't seem to have a source in your code above.
I put together a possible sample of what It may look like. I also moved your upload routine from the body of your code to the top for readability.
<CFIF IsDefined("form.upload_now")>
<CFIF structKeyExists(form, "ul_path") and len(form["ul_path"])>
<!--- assuming you need to lookup info from the database --->
<cfquery name="getThisLocation">
SELECT FolderID, FolderName, dir
FROM Locations
where foldername=#form.folderid#
</cfquery>
<CFFILE ACTION="UPLOAD" FILEFIELD="ul_path"
DESTINATION="C:\Documents\#getThisLocation.dir#\"
NAMECONFLICT="OverWrite">
<CFSET ClientFilePath = "#getThisLocation.clientDirectory#\##getThisLocation.clientFile#">
</CFIF>
</CFIF>
<cfquery name="getLocation">
SELECT *
FROM Locations
ORDER BY FolderName
</cfquery>
<form action="docuploads.cfm" method="POST" enctype="multipart/form-data" name="upload_form" id="upload_form">
<CFIF IsDefined("form.upload_now")>
<CFIF structKeyExists(form, "ul_path") and len(form["ul_path"])>
<P>FILE UPLOADED</P>
</CFIF>
</CFIF>
<select name="folderID">
<option value="">--- Select Folder ---</option>
<cfoutput query="getLocation">
<option value="#FolderName#"">#FolderName#</option>
</cfoutput>
</select>
<br /><br />
Click on the Browse button to select the file to Upload:<br>
<input type="file" name="ul_path" id="ul_path" style="height: 22px;width: 350px;" value=""><br><br>
<input type="submit" name="upload_now" id="upload_now" value="Submit" style="height: 22px;">
<input type="button" name="clear" value="Clear" style="height: 22px;">
<br /><br /><br />
</form>
I also added a snippet of code to let the user know that the file has been uploaded.
Please try this:
<CFIF IsDefined("form.upload_now")>
<CFIF structKeyExists(form, "ul_path") and len(form["ul_path"])>
<CFFILE ACTION="UPLOAD" FILEFIELD="#form.ul_path#"
DESTINATION="C:\Documents\#dir#\"
NAMECONFLICT="OverWrite">
<CFSET ClientFilePath = "#clientDirectory#\#clientFile#">
</CFIF>
<cfoutput>file uploaded successfully</cfoutput>
</CFIF>
<cfquery name="getLocation">
SELECT *
FROM Locations
ORDER BY FolderName
</cfquery>
<form action="docuploads.cfm" method="POST" enctype="multipart/form-data" name="upload_form" id="upload_form">
<select name="folderID">
<option value="">--- Select Folder ---</option>
<cfoutput query="getLocation">
<option value="#FolderName#"">#FolderName#</option>
</cfoutput>
</select>
<br /><br />
Click on the Browse button to select the file to Upload:<br>
<input type="file" name="ul_path" id="ul_path" style="height: 22px;width: 350px;" value=""><br><br>
<input type="submit" name="upload_now" id="upload_now" value="Submit" style="height: 22px;">
<input type="button" name="clear" value="Clear" style="height: 22px;">
<br /><br /><br />

coldfusion problem with flash form binding

i have the following :
<cfquery name="getArt" datasource="cfartgallery">
select * from art where artid < 10
</cfquery>
<cfform name="myform2" width="620" height="750" timeout="100" preservedata="yes" wmode="transparent">
<cfoutput query="getArt">
<cfinput id="pickers#currentRow#" name="pickmany" type="checkbox" value="#artname#" >
<label for="pickers#currentRow#">#artname#</label>
<br/>
</cfoutput>
<cfinput type="text" name="pickmany_selected" bind="{pickmany}" size="50">
</cfform>
whenever you check a box, it adds to the "pickmany_selected" field.
now, i am trying to do the same behaviour with a flash form.
<cfform name="myform" width="620" height="750" format="Flash" timeout="100" preservedata="yes" wmode="transparent">
<cfoutput query="getArt">
<cfinput id="pickers#currentRow#" name="pickmany" type="checkbox" value="#artname#" label="#artname#"><br/>
</cfoutput>
</cfform>
this breaks. it only works if i put name="pickmany#currentRow#":
<cfform name="myform" width="620" height="750" format="Flash" timeout="100" preservedata="yes" wmode="transparent">
<cfoutput query="getArt">
<cfinput id="pickers#currentRow#" name="pickmany#currentRow#" type="checkbox" value="#artname#" label="#artname#"><br/>
</cfoutput>
<cfinput type="text" name="pickmany_selected" bind="{pickmany1}" size="50">
</cfform>
what do i need to do for the flash form so that pickmany_selected binds correctly? in the last example, i cannot bind to a generic name. hate these flash forms.
it only works if i put
name="pickmany#currentRow#":
Yes, flash forms require all field names to be unique. Because of that, I suspect your goal is not possible with a bind. However, you could roll your own function and call it onClick. My flash skills are pretty rusty. But something along these lines:
<cfform name="myform" width="620" height="750" format="Flash" timeout="100" preservedata="yes" wmode="transparent">
<cfformitem type="script">
function updateSelectedArt():Void{
var elem;
var values = [];
var total = parseInt(myform.pickmany_total);
for (var i = 1; i <= total; i++) {
elem = _root["pickmany"+ i];
if (elem.selected) {
values.push(elem.label);
}
}
// use whatever delmiter makes sense
_root["pickmany_selected"].text = values.join(",");
}
</cfformitem>
<cfoutput query="getArt">
<cfinput name="pickmany#currentRow#" type="checkbox" value="#artname#" onClick="updateSelectedArt()" label="#artname#"><br/>
</cfoutput>
<cfinput type="hidden" name="pickmany_total" value="#getArt.recordCount#">
<cfinput type="text" name="pickmany_selected" value="" size="50">
</cfform>

Preserving input value of type="file" in ColdFusion on postback

I have a form in ColdFusion that initially has 5 input fields for file uploading. Should the user realize they have more than 5 files to upload in the process of attaching them, I would like the form to preserve the values when it submits itself for the change in # of fields.
Using the <cfform> tag with the preservedata="yes" attribute is supposed to accomplish this - but all I'm getting is a temp value stored in the input's value on resubmit that isn't displayed in the field nor works for a submission.
edit: Thanks for the great answers everyone, you all helped and were correct. I was able to implement Adam's suggested solution. Works great! Thanks!
function changeFieldCount() // javascript function for submit on input count change
{
var count = document.forms[0].numtotal.options[document.forms[0].numtotal.selectedIndex].value;
document.forms[0].action = "me.cfm?count=" + count;
document.forms[0].submit();
}
<cfparam name="url.count" default="5">
<cfform name="dispfiles" method="post" enctype="multipart/form-data" preservedata="yes">
<!--- looping for file input fields --->
<cfloop index="counter" from="1" to="#url.count#">
<cfinput type="file" name="file#counter#" size="50" maxlength="60"><br>
</cfloop>
<br>Number of Files to Attach:
<!--- looping for # of input selection--->
<cfselect name="numtotal">
<cfloop index="cnt" from="1" to="20" step="1">
<cfoutput>
<option value="#cnt#" <cfif #cnt# eq #url.count#>selected</cfif>>
#cnt#
</option>
</cfoutput>
</cfloop>
</cfselect>
<cfinput type="button" name="op-display" value="Display" onclick="changeFieldCount()">
<cfinput type="button" name="op-upload" value="Attach Files" onclick="submitfrm(this.form)">
<cfinput type="button" name="cancel" value=" Cancel " onclick="window.close()">
</cfform>
This is what I'm getting when I view source on the resulting submission:
<input name="file1" id="file1" type="file" value=".../cfusion.war/neotmp8858718543274653167.tmp" maxlength="60" size="50" /><br>
This is by design in all browsers for security reasons. There is no way you can insert the value for a file field.
To elaborate on #SpliFF's answer, what you need to do is dynamically create more file fields with JavaScript.
Here's an example that uses jQuery to make the JavaScript a little easier. I've also used a variable to track the number of file fields displayed so that they all have a unique number appended to their names, making it possible to loop over and uniquely identify them server-side.
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
//track the current number of file fields displayed
var numUploadFields = 5;
//attach an anonymous function to the button to add more fields
$(function(){
$("#add5").click(function(){
for (var i = 0; i < 5; i++){
numUploadFields += 1;
var newHTML = "<br/><input type='file' name='upload" +
numUploadFields + "' />";
$("#someSection").append(newHTML);
}
});
});
</script>
<form method="post" action="">
<div id="someSection">
<input type="file" name="upload1" /><br/>
<input type="file" name="upload2" /><br/>
<input type="file" name="upload3" /><br/>
<input type="file" name="upload4" /><br/>
<input type="file" name="upload5" />
</div>
<input type="button" id="add5" value="Add 5 more file fields" />
</form>
Build additional file inputs using JS DOM methods. Since you aren't leaving the page this is fast and nothing is lost.