How can I keep form values without using session? - coldfusion

I have one form page with pagination. I want to keep the form values as the user goes to the previous or next page, using pagination. I know that it can be done using the session scope. However, here I don't want to use session scope. Does anyone have any ideas on how to do this without using session? Please let me know.
Here is my form page:
<cfoutput>
<form action="#buildUrl(action='survey.save_surveyresults',querystring='surveyId=#rc.surveyid#')#" method="post">
<input type="hidden" name="id" value="0">
<input type="hidden" name="surveyid" value="#rc.surveyId#">
<div class="container-fluid">
<div class="row">
<div class="control-group">
<label class="label-control" for="name">Name</label>
<div class="controls">
<input type="text" name="name" id="name" required="true" placeholder="enter your name" value="#rc.name#">
</div>
</div>
<div class="control-group">
<label class="label-control" for="email">Email</label>
<div class="controls">
<input type="text" name="email" id="email" required="true" placeholder="enter your Email" value="#rc.email#">
</div>
</div>
<cfloop query="rc.questions" startrow="#startrow#" maxrows="#perpage#">
<!--- because we have all questions and answers in query we can use switch instead calling template or view
for each question, so its simplify directory structures, questions directory is not necessary now --->
<h3>#CurrentRow#<cfif rc.questions.isrequired><strong>*</strong></cfif>. #rc.questions.question#<h3>
<cfswitch expression="#rc.questions.template#">
<fieldset>
<cfcase value="textbox">
<input type="text" class="input-xlarge" name="#template#_#questionid#" id="question_#questionid#">
</cfcase>
<cfcase value="multiplechoice">
<cfloop list="#answer#" delimiters="," index="i">
<div class="controls">
<label>
<input type="radio" name="#template#_#questionid#" id="question_#questionid#" value="#answerID#" >
<span class="lbl">#i#</span>
</label>
</div>
</cfloop>
</cfcase>
<cfcase value="multiplechoiceother">
<cfloop list="#answer#" delimiters="," index="i">
<div class="controls">
<label>
<input type="radio" name="#template#_#questionid#" id="question_#questionid#" value="#answerID#" >
<span class="lbl">#i#</span>
</label>
</div>
</cfloop>
<div class="control-group">
<label class="label-control" for="other">Other</label>
<div class="controls">
<input type="text" class="input-xlarge" name="#template#_#questionid#" id="question_#questionid#">
</div>
</div>
</cfcase>
</fieldset>
</cfswitch>
</cfloop>
<p></p><br />
<cfif startrow GT 1>
Previous
</cfif>
<cfif (startrow + perpage - 1) lt rc.questions.recordcount>
Next
<cfelse>
<button type="submit" name="submit" class="btn btn-success">Finish</button>
</cfif>
</div>
</div>
</div>
</form>
</cfoutput>

You could break the form up into different sections and have it all in one page. You can hide/show parts of the form using JavaScript based on which 'page' of the form they are one.
This makes going forward or backward in the form a snap since it is not submitted until they are done with the whole form and the values they entered will still be there.. and is pretty easy to handle with jQuery or other JavaScript libraries.

As Dan said - save submitted values in hidden fields.
One issue I see with your HTML is that Previous/Next pages are just links - not submit buttons. So make sure that when clicking those links users are submitting the form - not just going to a different url.

Here's a simple snippet of code that will embed all your form variables into hidden fields. You would place this code inside the form handler on the page you are submitting to. Note Lucas' answer as well. Your form may not be submitting correctly for reasons of badly formed..er...form.
<Cfloop collection="#form#" item="fItem">
<cfoutput>
<input type="hidden" name="#fItem#" value="#form[fItem]#"/>
</cfoutput>
</cfloop>
Again .. this would go _inside" of the form on the subsequent page. This is fairly common in multipart forms (shopping carts with multiple steps, profile entries etc).

Bear in mind that with the approaches above, you need to re-validate your form values on the server side every time you submit them (or at the very least before your final processing).
What you make up for in server memory, you may lose in terms of traffic and load times, depending on scale so I would advise that you proceed with caution. Increasing production traffic unnecessarily can result in financial impacts, and often server memory can be cheaper than extended increased traffic outlay; it comes down to your requirements and scale at the end of the day.
Shipping form variables around also increases your attack surface for malicious injection of form data, so while you may be concerned with session variables being altered on you (curious to hear more on this), you are already opening yourself up by shipping this data around as plain text. Do not rely on client-side validation for this (or any) data.

Related

2 Submit buttons in 1 form

I have 2 submit buttons in my form.
<input type="submit" value="Save as Draft">
<input type="submit" value="Save">
Basically, what I want to do is when the user clicks on Save as Draft, it will proceed to bring all the form details to _update.cfm (without validating) and when the user clicks on Save, it will proceed to _validate.cfm and then to _update.cfm(validating and updating the database.)
HTML:
<cfset tx_name = "">
<cfif isDefined("form.tx_name")>
<cfset tx_name = form.tx_name>
</cfif>
<cfinclude template="_validate.cfm">
<cfif isDefined("form.tx_name")>
<cfinclude template="_update.cfm">
</cfif>
<form name="something">
<input type="text" name="tx_name" value="#tx_name#">
<input type="submit" value="Save as Draft">
<input type="submit" value="Save">
</form>
So basically what the above form does is that, by default, tx_name = " " and when user types something and submits, it will do all the validation in _validate.cfm and then proceed to _update.cfm to update it.
This is the intended way to work when the user clicks on Save button. However, for Save as Draft, I would like it to skip the _validate.cfm and straight bring all the form field data to _update.cfm.
The following is what I tried:
Attempt 1:
Instead of having <input type="submit" value="Save as Draft">, I used <input type="button" value="Save as Draft" onClick="location.href='_update.cfm';". And this didn't bring the form fields to _update.cfm and I figured out the reason, its because it is just redirecting to _update.cfm upon clicking the button.
So this made me think that I really need a submit button (to bring form data to the _update.cfm page).
But here is where I am lost as I have now 2 submit buttons. 1 of it is to work with _validate.cfm and the other to work without _validate.cfm.
So how do I go about to make Save as Draft not validate but update and Save to validate and update?
I would go down the road of both buttons having the same name, but a different value. I would also use button tags so that I could have better control over the display vs the value submitted. I would then not have to deal with if the display needs change, I would not have to change the processing. Last but not least I would wrap it so that it only operates in post
<cfscript>
if (cgi.request_method == "post") {
if (form.keyexists("tx_name") tx_name = form.tx_name;
if form.SaveMode == "Save") include "_validate.cfm";
if (form.keyexists("tx_name") include "_update.cfm";
}
</cfscript>
<form name="something" method="post">
<input type="text" name="tx_name" value="#tx_name#">
<button type="submit" name="SaveMode" value="Save as Draft">Save As Draft</button>
<button type="submit" name="SaveMode" value="Save">Save</button>
</form>
For that you have to add name for the two submit buttons. And using that name we can prevent the _validate.cfm inclusion, while submitting the form through clicking "Save as draft" button.
Also the form method should be POST, so that form scope will be available on action page, otherwise it'll available in URL scope.
<cfset tx_name = "">
<cfif isDefined("form.tx_name")>
<cfset tx_name = form.tx_name>
</cfif>
<cfif isdefined("form.Save")>
<cfinclude template="_validate.cfm">
</cfif>
<cfif isDefined("form.tx_name")>
<cfinclude template="_update.cfm">
</cfif>
<form name="something" method="post">
<input type="text" name="tx_name" value="#tx_name#">
<input type="submit" name="SaveAsDraft" value="Save as Draft">
<input type="submit" name="Save" value="Save">
</form>
I use a hidden form field called action. On the buttons I attach an onClick to change the value of action. On the form's action page I read that value and determine what to do. EX:
<input type="hidden" name="action" value="save" id="action">
<button type="submit" class="button button-basic-green" onclick="document.getElementById('action').value='save';"><span class="fa fa-save"></span> Save</button>
<button type="submit" class="button button-basic" onclick="document.getElementById('action').value='reload';"><span class="fa fa-repeat"></span> Save & Reload</button>
<button type="submit" class="button button-basic" onclick="document.location.href='./';return false;"><span class="fa fa-arrow-circle-o-left"></span> Cancel</button>

Accessing variables of a dynamic form

I am creating a form with cfloop and need to access each variable individually when submitting the form. I need to use the selected entries of the form in a loop that will add my selections to a database.
This is my form:
<form method="post">
<input type="hidden" name="isPost" value="1">
...
<cfoutput>
<cfloop query="client_admin_surveys">
<input type="text" size="35" name="surveyID" id="surveyID" value="#id#">
<input type="text" size="35" name="surveyName" id="surveyName" value="#name#">
<input type="checkbox" name="amplify" id="amplify">
<input type="checkbox" name="enchance" id="enchance">
<input type="checkbox" name="pacify" id="pacify">
<input type="checkbox" name="pacifyUrgent" id="pacifyUrgent">
</cfloop>
</cfoutput>
...
<input type="submit" name="submit" value="Submit">
</form>
After posting the form, the results group all of my selections because I have the same "name" for my form elements. I tried adding an i count next to each name to make it different but then I got a bit confused about how to process the fields.
You started down the correct path when you added the counter - go back and add that, something like:
<input type="checkbox" name="amplify#client_admin_surveys.currentRow#" id="amplify">
Would work.
I also sometimes like to add a form field for the 'counter' on the processing page
<input type="hidden" name="counter" value="#client_admin_surveys.recordCount#" />
Then on the processing page, you can loop over the counter and access the form fields using bracket notation
<cfloop from="1" to="#form.counter#" indexd="i">
<cfset thisAmplify = form["amplify" & i] />
<cfset thisEnhance = form["enhance" & i] />
<!---- more logic here --->
</cfloop>

How to get the selected values

I am unable to figure out how to loop over the questionTypes and get selected questionType value. Based on the selected questionType I have to add answers for multioption questions, like in choose the correct answers we provide four choices out of which one we have to select as correct answer.
I have tried to use cfswitch but it does not seem to work:
<html>
<head> <script src="http://code.jquery.com/jquery-latest.js"></script></head>
<body>
<cfoutput>
<cfif not IsDefined('rc.questionType')>
<form class="form form-horizontal" action="#buildUrl('question.new')#" method="post">
<input type="hidden" name="surveyId" value="#rc.surveyId#">
<fieldset>
<div class="control-group">
<label class="control-label" for="questiontype">Question type</label>
<div class="controls">
<select name="questionType" onchange="this.form.submit()">
<option value="0" >Select question type</option>
<cfloop query="rc.types">
<option value="#id#">#name#</option>
</cfloop>
</select>
</div>
</div>
</fieldset>
</form>
<!--- if question type is defined, display question form --->
<cfelse>
<form class="form form-horizontal" action="#buildUrl('question.save')#" method="post">
<input type="hidden" name="id" value="0">
<input type="hidden" name="surveyId" value="#rc.data.fksurveyId#">
<input type="hidden" name="questionTypeId" value="#rc.data.fkquestionTypeId#">
<input type="hidden" name="rank" value="#rc.data.rank#">
<fieldset>
<div class="control-group">
<label class="control-label" for="question">Question</label>
<div class="controls">
<input class="input-xxlarge" type="text" name="question" id="question" required="true" placeholder="write your question">
</div>
</div>
<div class="control-group">
<label class="control-label" for="Required">Required</label>
<div class="controls">
<select name="Required">
<option value="1" selected>Yes</option>
<option value="0">No</option>
</select>
</div>
</div>
<!--- question arguments for selected type, this will be for multioption questions --->
<!--- <cfif rc.questiontype is "multiple choice (single selection),Multiple Choice (Multi Selection) with Other,Multiple Choice (Single Selection) with Other,Multiple Choice (Multi Selection)"> --->
<cfswitch expression="#rc.questiontypeid#">
<cfcase value="multiple choice (single selection),Multiple Choice (Multi Selection) with Other,Multiple Choice (Single Selection) with Other,Multiple Choice (Multi Selection)">
<div class="control-group">
<label class="control-label" for="answer">Answer</label>
<div class="controls">
<input class="input-xxlarge" type="text" name="new_answer" id="new_answer">
</div>
</div>
<div class="control-group">
<label class="control-label" for="rank">rank</label>
<div class="controls">
<input class="input-mini" type="text" name="rank" id="rank">
</div>
</div>
<div class="control-group">
<label class="control-label" for="answer">Answer</label>
<div class="controls">
<input class="input-xxlarge" type="text" name="new_answer" id="new_answer">
</div>
</div>
<div class="control-group">
<label class="control-label" for="rank">rank</label>
<div class="controls">
<input class="input-mini" type="text" name="rank" id="rank">
</div>
</div>
</cfcase>
</cfswitch>
<!--- --->
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save</button>
Cancel
</div>
</fieldset>
</form>
</cfif>
<cfdump var="#rc#">
</cfoutput>
</body>
</html>
This is my controller method to add a new question:
<cffunction name="new" returntype="void" access="public">
<cfargument name="rc" type="struct" required="true">
<!---call service to get the textfields, checkboxes etc,. based on questiontype selection --->
<!--- call service to get question types for select box --->
<cfset rc.types = getQuestionService().types()>
<cfset rc.action = 'New Question'>
<!--- if user select question type --->
<cfif isdefined('arguments.rc.questionType')>
<cfset rc.data = getQuestionService().new(arguments.rc.surveyId, arguments.rc.questionType)>
</cfif>
</cffunction>
I have two forms in single page. In the first form I am selecting questionType. Based on the selected questionType I have to display an add question form.
To make sure I'm reading how this code is supposed to work:
1. This is a form to create the question, not answer it.
2. rc is a struct with your basic question definition as the keys and you have other existing code that insures that the rc structure will exist on this page.
(Rather than isDefined("rc.questionType") I'd use structKeyExists(rc, "questionType"), but that's a whole different discussion.
3. When you change the value of the Question Type, that field is submitted back and other code creates and populates the questionType key of rc struct. So isDefined('rc.questionType') should now be TRUE (moving you to the cfelse block).
4. You are now brought back to the same page with a field to enter the question, whether it's required, and you're looking for the Answer entry boxes based on the questionType.
If all of those assumptions are correct, then this is the point that you would need to loop through your options for your answers. The cfswitch/cfcase is correct, but some of those multiple choice options will need to be handled slightly differently. The ones with "Other" options will need slightly more processing on this end and on the answer tracking end. You'll have to add a text box for that checked answer.
So you'll need a little more definition for the questions in the rc struct. You need to track which one is the correct answer (a simple checkbox). If you want to allow a dynamic number of multi-choice answers, you'll need to keep track of how many answers you'll need. And you could even keep these multi-choice answer options together if you tracked whether the answer was an "Other" or not. This would also allow you to have multiple "Other"-type selections in the multi-choice options. Granted, that would reduce your choices for whether this is a multi-choice question down to just one, simply "Multiple Choice". Let the answers determine whether it's single selection or "Other" selection. And if you wanted to use radio buttons instead of check boxes for the single selects, all you'd have to do is count the answers for the question. Then you can worry about each basic questionType seperately.
The code to better track the answers (correct and "Other" options) will also need to be pulled back up, likely in the getQuestionService() function, which is where I'm assuming you're pulling your question definition and populating the rc struct.
Do you plan on using this form as an UPSERT, or is this simply an INSERT and you'll UPDATE/EDIT the questions elsewhere?
Regardless, back to your original question. The first thing I'd recommend would be to also cfdump the rc struct at the top of the page. See what data you're initially working with.
Down where you need to add your Answers, the cfswitch is the correct method. You likely aren't matching any of your cases here. Output rc.questionTypeID here to see what your value is. And I'd use an integer ID for the question type rather than the name of the question type. It'll give faster, more precise processing. When you get the correct case, you'll need to cfloop your answers here.
To select which one is the correct one, simply add a selected="selected" or checked="checked" (depending on input type) inside of a cfif that checks if the current answer is the correct answer.
Since the switch expression is set to rc.questiontypeid, the case value should be the possible rc.questiontypeid, not the question type name.

displaying questions twice

can anyone review this code tell me what's wrong in it? I don't understand why it is displaying questions two times.
here is the code to display questions based on its questiontype, I mean it will look into question folder for matching questiontype template and then display it with question.
this is the code to show survey's questions.
<cfoutput>
<cfset step = 0 />
<form class="form form-horizontal" action="#buildUrl(action='survey.savesurveyresults',querystring='surveyId=#rc.surveyid#')#" method="post">
<input type="hidden" name="id" value="0">
<input type="hidden" name="fksurveyid" value="#rc.surveyId#">
<input type="hidden" name="fkquestionid" value="#rc.questions.id#">
<fieldset>
<cfloop query="rc.questions">
<cfset step ++ />
<cfset answer = "" />
<cfmodule template="../question/#rc.questions.template#/display.cfm" step="#step#" question="#rc.questions.question#" template1="#rc.questions.template#" fkquestionid="#rc.questions.id#" answer="#answer#" required="#rc.questions.required#" result="result#step#"/>
</cfloop>
<div class="form-actions">
<button type="submit" name="submit" class="btn btn-success">Submit answers</button>
</div>
</fieldset>
</form>
</cfoutput>
this is my display.cfm to view question and its questiontype like truefalse or yes or no.
<cfparam name="attributes.yesno" default="false">
<cfoutput>
<p>#attributes.step#) #attributes.question# <cfif attributes.required EQ 1><strong>* </strong></cfif></p>
<div class="answers">
<cfif attributes.yesno>
<input type="radio" name="answer" id="answer" value="yes"<cfif attributes.answer is "yes">Checked</cfif>><label for="truefalse">Yes</label><br>
<input type="radio" name="answer" id="answer" value="no"<cfif attributes.answer is "No">Checked</cfif>><label for="truefalse">No</label>
<cfelse>
<input type="radio" name="answer" id="answer" value="true"<cfif attributes.answer is "true">Checked</cfif>><label for="truefalse">True</label><br>
<input type="radio" name="answer" id="answer" value="False"<cfif attributes.answer is "False">Checked</cfif>><label for="truefalse">False</label>
</cfif>
</div>
</cfoutput>
here is the query to list question's records.
<cfquery name="list">
SELECT
questions.id,
questions.question,
questions.rank,
questions.required,
questiontypes.name as questiontype,
questiontypes.template as template,
surveys.name as surveysname,
surveys.thankyoumsg as thankyoumsg
FROM questions
INNER JOIN questiontypes ON questions.fkquestiontypeid = questiontypes.id
INNER JOIN surveys ON questions.fksurveyid = surveys.id
WHERE questions.fksurveyid = <cfqueryparam cfsqltype="cf_sql_bigint" value="#arguments.surveyid#">
</cfquery>
This is something that has bitten me a couple of times. I've always been pretty big on closing tags. But this is a situation where it will hurt. And be hard to debug if you don't understand the behavior of cfmodule. As the post above mine states, if you close the cfmodule tag, it will execute twice. This is because it's treated the same as a custom tag. There may be situations where you want to process part of the tag when it's first run and the rest after it's complete. You can access the ExecutionMode in the thisTag scope of the cfmodule page. With no closing tag, it's simply run in the thisTag.ExecutionMode = Start mode. If you close it, it runs the tag again in the End mode. If you aren't doing anything with the ExecutionMode inside the cfmodule's code, the whole thing will simply run again. This behavior is part of the reason that cfmodule can be so powerful.
When using the <cfmodule> tag you need to remember that ColdFusion will call that tag twice if you include an ending </cfmodule> tag OR if you close the opening tag like so <cfmodule ... />.
As stated on the cfmodule documentation page:
If you specify an end tag to cfmodule, ColdFusion calls your custom tag as if it had both a start and an end tag. For more information, see Handling end tags in the Developing ColdFusion Applications.
Handling end tags in the Developing ColdFusion Applications
In order to avoid this functionality do not close your <cfmodule> tag.
I got it, i must have not to close the cfmodule tag like <cfmodule />.

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.