Solved

ColdFusion Form Data

Posted on 2011-03-15
5
340 Views
Last Modified: 2012-05-11
Hi,
 I am very new to cold fusion but need to handle an issue. I have a form page in cold fusion, when we enter the data in the form and press submit button  it has to insert that data into the table in database.

Can anyone please please help me with this thing.
0
Comment
Question by:new_perl_user
  • 3
  • 2
5 Comments
 
LVL 39

Accepted Solution

by:
gdemaria earned 500 total points
ID: 35139650
Here's a basic framework for a beginner-intermediate user.   Posting a form page to itself makes life easy and gives you some power.   The way it works is that you have a CFIF at the top of the page to process the action of the form submit.  But the first time the page loads, the form is not submitted, so this part is skipped.  The data is fetched from the able, copied into FORM.xxx scope variables and displayed in the form.  On submit, the same page is called, the action is processed.  If there is an error, it will display along with the form -with the same data the user entered - (not a refresh from the database).   If there is no error, then using CFLOCATION, you can go to any other page...

Take a look and ask questions, if you can get the hang of this is will be very usefull model for all pages...


<!--- this is the primary key for the data on this page, expect it to be passed, 
      if it is empty, the page will create a new record ----->
<cfparam name="form.contact_id" default="">  
		  
<cfset variables.error = "">  <!---- this variable will hold an error message, if a problem occurs ---->

<cfif IsDefined('form.submit')>  <!-- the page has been submitted, process action --->
  <cftransaction action="BEGIN"> <!--- a transaction ensure everything on page is saved together or rolledback on error ---->
  <cftry>  <!---- catch any errors in the cfcatch below ----->
   <cfloop index="ii" list="lastname,firstname,email">  <!--- validate required fields are not empty --->
     <cfif len(form[ii]) eq 0>
	    <cfthrow message="Please supply all required fields">
	 </cfif>
   </cfloop>
   <cfinclude template="owner_upd.cfm"> <!--- this file inserts or updates the data --->
   <cftransaction action="COMMIT">
  <cfcatch type="Any"> <!---- catch all errors, whether you cfthrow them or if happens in your sql statements ---->
     <cftransaction action="ROLLBACK">
     <cfset variables.error = cfcatch.message> <!---- set your error flag message variable ---->
  </cfcatch>
  </cftry>
  </cftransaction>
  <cfif len(variables.error) eq 0> <!--- if no error, go to your next page ---->
     <cflocation url="/nextpage.cfm?ID=AddVariablesHere" addtoken="no">
  </cfif>
</cfif>

<cfif len(variables.error) eq 0> <!--- this happens on first opening the file, get data ---->

   <cfquery name="getContact" datasource="#request.datasource#">
     select * from contacts
	 where contact_id = #val(form.contact_id)#
   </cfquery>
   <!---- the next line will copy every column from the query into a FORM
          variable.  This will allow you to use the form scope below instead
		  of the query name.  In case of an error, this allows your page
		  to reload the entered values without saving them ---->
   <cfloop index="ii" list="#getContact.columnList#">
      <cfset form[ii] = getContact[ii][getcontacts.currentRow]>
   </cfloop>
   
</cfif>

<cfif len(variables.error) gt 0> <!--- if an error, show it ---->
  <cfoutput><span style="color:red">#variables.error#</span></cfoutput>
</cfif>
<!--- here is your form to get the data ---->

<cfoutput>
<form method="post">  <!---- No Action in form, page will post to itself ---->

 First Name: <input type="Text" name="firstName" value="#form.firstName#"><br><br>
 
 Last Name: <input type="Text" name="LastName" value="#form.lastName#"><br><br>

 Email: <input type="Text" name="email" value="#form.email#"><br><br>

 <input type="Submit" name="submit" value="Save">

</form>
</cfoutput>

Open in new window

0
 
LVL 15

Expert Comment

by:myselfrandhawa
ID: 35147016
Wow! @gd Very Good and Great Way to handle the data insertion on single Page, Good Work!

Here is another Simple Technique!

No Points!

The Below code with small changes can be reused to the Update Statement as Well!




<cfparam name="firstname" default="">
<cfparam name="lastname" default="">
<cfparam name="email" default="">
<cftry>
<cfif StructKeyExists(FORM,'Save')>
	<cfif len(form.firstname) IS 0>
		<cfset s = "Error! Please Provide First Name">
	<cfelseif len(form.lastname) IS 0>	
		<cfset s = "Error! Please Provide Last Name">
	<cfelseif IsValid("email",form.email)>	
		<cfset s = "Error! Provide Valid Email Address">
	<cfelse>
		<cftransaction action="begin">
			<cftry>
				<cfquery datasource="test">
				insert into temp1(firstname,lastname,email) 
				values('#form.firstname#','#form.lastname#','#form.email#')
				</cfquery>
			<cftransaction action="COMMIT"/>
				<cfcatch type="Any"> 
				     <cftransaction action="ROLLBACK"/>
					     <cfset s = cfcatch.message> 
	  			</cfcatch>
			</cftry>
		</cftransaction>
	</cfif>	
</cfif>
<cfcatch>
	<cfset s = "Error! #cfcatch.Detail# #cfcatch.message#">
</cfcatch>
</cftry>
<cfoutput>
	<cfif isDefined('s')>
		<div align="left">#s#</div>
	</cfif>
<form method="post">  <!---- No Action in form, page will post to itself ---->
First Name: <input type="Text" name="firstName" value="#firstName#"><br><br>
Last Name: <input type="Text" name="LastName" value="#lastName#"><br><br>
Email: <input type="Text" name="email" value="#.email#"><br><br>
<input type="Submit" name="submit" value="Save">
</form>
</cfoutput>

Open in new window

0
 
LVL 15

Expert Comment

by:myselfrandhawa
ID: 35147023
change the line

Email: <input type="Text" name="email" value="#.email#"><br><br>

to

Email: <input type="Text" name="email" value="#email#"><br><br>
0
 
LVL 39

Assisted Solution

by:gdemaria
gdemaria earned 500 total points
ID: 35147979
Thanks myselfrandhawa for pointing out that the insert/update code does not show (I included it using cfinclude).   The code would look the following.   It allows for insert or update of records depending on whether or not the primary key (ID) already exists..

myselfrandhawa, not sure why you would want to change the variable name from a nice, clear "error" to an  "s" ?   SidFishes, another expert on EE, calls those "Lazy Variables"  (love that!)   You are better off having distinctive names.  Also, imagine searching for the variable "S"... you would match TONS of letters through out your code making it very hard to find where "S" is actually used.


** Put this code in where I have <cfinclude template="owner_upd.cfm">  
** Or better yet create a file and put this code in it, so it can be shared
** The form page does BOTH add a record and Modify an existing record

             <cfif val(form.contact_id)> <!---- record exists, update it ---->
				<cfquery datasource="test">
				  update contacts
                    set firstname = <cfif len(form.firstname)>'#form.firstname#'<cfelse>NULL</cfif>
                       ,lastname = <cfif len(form.lastname)>'#form.lastname#'<cfelse>NULL</cfif>
                       ,email = <cfif len(form.email)>'#form.email#'<cfelse>NULL</cfif>
				  where contact_id = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#val(form.contact_id#">
				</cfquery>
             <cfelse> <!--- record doesn't exist, insert it ---->
				<cfquery datasource="test">
				insert into contacts (firstname,lastname,email) 
				values('#form.firstname#','#form.lastname#','#form.email#')
				</cfquery>
             </cfif>

Open in new window

0
 
LVL 15

Expert Comment

by:myselfrandhawa
ID: 35148238
Woo just my 2 cents I love those lazy variables :)
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Setting a variable in Cold Fusion 15 52
Sending Text Messages 1 48
multi page pdf 4 69
ColdFusion 10 Error 2 23
This article  is about submitting  form through  ColdFusion.Ajax.submitForm to the action page and send a response back in JSON format which later can be decoded using ColdFusion.JSON.decode. By this way you can avoid the usual page refresh for subm…
Today, I was working on some optimization and spam-stopping techniques when I encountered Ben Nadel's post to reduce spam feature using Math (http://www.bennadel.com/blog/197-How-I-Stop-Spammers-On-My-ColdFusion-Blog.htm). While this method is not o…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now