Coldfusion Examples

Google
 
Web cftutorial.blogspot.com

Wednesday, August 09, 2006

Creating Web pages in Coldfusion

1. What is Application.cfm file in Coldfusion?

Application.cfm file is very important and special file for Web Application framework.
The basic function performed by this file is, the code of this file is automatically executed just before each of the pages that make up your application.

In simple words “The code of Application.cfm file will be automatically included just before any of your application pafes.” The behavior is the same as if you included the file using <cfinclud> tag.

So whenever a user visits a .cfm pade, coldfusion looks to see whether a file named Application.cfm exists in the same directory as the requested page. If so coldfusion automatically includes it.

If coldfusion could not found the file in the same folder then it looks in that folder’s parent folder. It will keep looking into these folders until there are no more parent folders to look into.


Sample Application.cfm file:

// Any variable set here can be used by all pages
// Start session management. Used to track session variables

<cfset this.sessionManagement = true>

// Start client management. Used to track client variables

<cfset this.clientmanagement = true>
<cfset this.name = "Name of your application">


<!--- On Request Start Function--->
// is called when user request any web page.

<cffunction name="onRequestStart" output="true" returntype="void">
<cfset request.datasource = "companyk1" >
<cfset request.companyname = "Company K1 - HQ">

/* call your header file everytime when user access webpage. So you do not have to include in every page*/
<cfinclude template="companyk1_header.cfm">

</cffunction>

/*On request end function is used to called end the end of webpage access */

<cffunction name="onRequestEnd" returntype="void" output="true">
<cfinclude template="companyk1_footer.cfm">
</cffunction>


2. How to fetch records from database using coldfusion application?

Assume: Table name = “profile” and it has ID, LastName, FirstName, FirstTime etc Column name.
Value of “FirstTime” field will be 0 or 1.


/* Just before start of Body tag */

<cfquery name="getUser" datasource="#request.datasource#">
select ID, LastName, FirstName, FirstTime from profile
where Username = 'gaurang' and Password= 123456
</cfquery>

<body&gy;
<cfoutput query=”getUser”>
<table>
<tr>
<td>#getUser.ID#</td>
<td>#getUser.FirstName#</td>
<td>#getUser.LastName#</td>
<td>#getUser.FirstTime#</td>
</cfoutput>
</body&gy;

Result:
1 Gaurang Patel 0


3. How to make login page in coldfusion such that if the user is the first time user then he will be forwarded to some other page for example “profile creation page” and if the user is existing user then he will be forwarded to some different page for example “main page”?

Code:

Step 1: Create Application.cfm file.

<cfset this.sessionManagement = true>
<cfset this.clientmanagement = true>
<cfset this.name = "BIOLOGY Department">

<cffunction name="onRequestStart" output="true" returntype="void">
<cfset request.datasource = "FlattenedFauna" >
<cfset request.companyname = "Company k1 - HQ">

<cfinclude template="Bio_header.cfm">

/* LoggedIn is a session variable which is used to restrict visitor from opening any page without login process. Below is the code to check that. If a user has pass through login process then “isLoggedIn” is true.

And if visior has not pass through login process and directly want to go to other pages then for that session “isLoggedIn” is not defined and so it is false and loginform.cfm page will open. */

<cfif not IsDefined("session.auth.isLoggedIn")>
<cfif IsDefined("form.userLogin")>
<cfinclude template="logincheck.cfm">
</cfif>
<cfinclude template="loginform.cfm">
<cfabort>
</cfif>

</cffunction>

<cffunction name="onRequestEnd" returntype="void" output="true">
<cfinclude template="Bio_footer.cfm">
</cffunction>


Step 2: Create loginform.cfm
Copy and Paste this within <body> </body> tag.

<cfform action="logincheck.cfm" name="LoginForm" method="post" >

<cfinput type="hidden" name="userLogin_required">
<cfinput type="hidden" name="userPassword_required">

<table border="0">
<tr><th colspan="2" bgcolor="#C0C0C0"><font face="Geneva, Arial, Helvetica, sans-serif" size="3" color="#003300">Please Log In </font></th></tr>

<tr>
<th><font face="Geneva, Arial, Helvetica, sans-serif" size="2" color="#003300">User Name :</font></th>

<td>
<cfinput type="text"
name="userLogin"
size="20"
value=""
maxlength="100"
required="yes"
message="Please Type your Username First"
style="border:1px solid ##000000; border-color:##000000; background-color:##FFFFCC" /></td>
<td>
<font face="Geneva, Arial, Helvetica, sans-serif" size="2" color="#003300">
Example : username@gmail.com</font></td>
</tr>

<tr>
<th><font face="Geneva, Arial, Helvetica, sans-serif" size="2" color="#003300">Password :</font></th>
<td>
<cfinput type="password"
name="userPassword"
size="12"
value=""
maxlength="100"
required="yes"
message="Please Type your Password First"
style="border:1px solid ##000000; border-color:##000000; background-color:##FFFFCC"/>
<cfinput name="btn_login" type="submit" value="Enter" style="border:1px solid ##000000; border-color:##000000;"/></td>
</tr>
</table>
</cfform>


Step 3: Create logincheck.cfm

Copy and paste this javascript within <head> </head> section



<script language="JavaScript" runat="server" type="text/javascript">
history.forward();
</script>

copy and paste within <body> </body> tag:


<cffile action="write" file="C:\track_login.txt" output="#form.userLogin#">

<cfif IsDefined("COOKIE.timeStart") EQ "NO">
<CFCOOKIE name="timeStart"
value="now()"
expires="now"></cfif>

<cfparam name="form.userLogin" type="string">
<cfparam name="form.userPassword" type="string">

<cfquery name="getUser" datasource="#request.datasource#">
select ID,LastName,FirstName,FirstTime from profile
where Username = '#form.userLogin#' and Password= '#form.userPassword#'
</cfquery>

<cfif getUser.recordcount eq 1>

<cfset session.auth = StructNew()>
<cfset session.auth.isLoggedIn = "1">
<cfset session.auth.id = getUser.ID>
<cfset session.auth.lastname = getUser.LastName>
<cfset session.auth.firstname = getUser.FirstName>

<cfif getUser.FirstTime eq 0>
<cflocation url="user_profile.cfm" addtoken="no">
<cfelse>
<cflocation url="name of url link to which you want to forward your visitor" addtoken="no">
</cfif>
</cfif>
<cflocation url="loginform.cfm" addtoken="no">


4. Change password web page using coldfusion?

Code:
step 1: change_pass.cfm
copy and paste below code in <head> </head> section

// This style is used to change background color when cursor moves on or moves out from button.
<STYLE>
.start {color:##006600; background:#999999;}
.end {color:##006600; background:##003300;}
</STYLE>
// Java script for changing background color.
<script type="text/javascript" >
function highlightButton(s)
{
// get the tagName for particular event. Here get input type of “BUTTON”. You can also use other input types instead of just button.
if ("INPUT"==event.srcElement.tagName)
event.srcElement.className=s // assign particular class style for particular event.
}



copy and paste below code in <body> </body> section

<cfform name="frm_pass_change" action="passchange_proc.cfm" method="post" onsubmit="return submitIt()">
<div align="center">

<table border="0">
<tr>
<td align="right">
Please Enter Your <font color="#003300" size="2" face="Verdana, Arial, Helvetica, sans-serif">Current</font> Password :</td>
<td>
<cfinput type="password" name="old_pass" style="border:1px solid ##000000; border-color:##000000; background-color:##FFFFCC" value="" size="20"/>
</td>
</tr>

<tr height="20">
</tr>

<tr>
<td align="right">
New Password:
</td>
<td>
<cfinput type="password" name="new_pass" style="border:1px solid ##000000; border-color:##000000" value="" size="20"/>
</td>
</tr>

<tr>
<td align="right">
Retype New Password :
</td>
<td>
<cfinput type="password" name="retype_pass" style="border:1px solid ##000000; border-color:##000000" value="" size="20"/>
</td>
</tr>
<tr height="20">
</tr>

<tr>
<td align="center" colspan="2">
<cfinput type="submit" value="Change It" name="btn_submit" style="border:1px solid ##333333; border-color:##000000;"
onMouseover="highlightButton('start')"
onMouseout="highlightButton('end')"/>
<cfinput type="reset" value="Reset" name="btn_reset" style="border:1px solid ##333333; border-color:##000000;"
onMouseover="highlightButton('start')"
onMouseout="highlightButton('end')"/>
</td>
</tr>
</table>
</td>
</tr>
<!--- Outer Tabel Ends here--->
</table>
</div>
</cfform>


Step 2: passchange_proc.cfm

// Paste this code before tag

// get your old password from profile table. Here #session.auth.firstname# and #session.auth.lastname# are the first and last name of user who is currently logged in.

<cfquery name="get_old_pass" datasource="#request.datasource#">
SELECT Password from profile where FirstName = '#session.auth.firstname#'
and LastName = '#session.auth.lastname#'
</cfquery>

// Update password if matched.
<cfif #form.old_pass# eq #get_old_pass.Password#>
<cfquery name="update_pass" datasource="#request.datasource#">
UPDATE profile
set Password = '#form.new_pass#'
where FirstName = '#session.auth.firstname#'
AND
LastName = '#session.auth.lastname#'
</cfquery>
<cflocation url="change_pass.cfm?pass_changed=1"/>

// Error message if current password is wrong.
<cfelse>
<cfoutput > <h1>Your Current Password is wrong.<br/>
Please Enter Correct Password.
<a href="change_pass.cfm">Try Again </a></h1></cfoutput>
</cfif>


5. How to use ListBox in coldfusion? Or How to add values in ListBox in coldfusion?

How to add values in Listbox statically without fetching from database.

<CFSELECT name="Species" width="100" style="border:1px solid ##000000; border-color:##000000; background-color:##FFFFCC" onChange="showimage()">
<option value="Deer">Deer</option>
<option value="Elk">Elk</option>
<option value="Bear">Bear</option>
<option value="Bighorn Sheep">Bighorn Sheep</option>
<option value="Coyote">Coyote</option>
</CFSELECT>


How to add values in Listbox dynamically, mean from database.


//table = "county_dist" Colunm name = "County"

<cfquery name="get_county" datasource="#request.datasource#">
SELECT DISTINCT County FROM county_dist
</cfquery>

<cfform name=”listbox”>
// value defines the name of column of table which values you want to use.
// display defines the name of column of table which values you want to display.
// multiple = “yes” allows you to select multiple values

<cfselect name="county" query="get_county" value="County" display="County" style="border:1px solid ##000000; background-color:##FFFFCC;" multiple="yes" size="3">
<option value="" selected="selected" >any</option>
</cfselect>
</cfform>


/*More Topics are coming soon */

Wednesday, July 26, 2006

Coldfusion Examples


Back to Home Page

What is Coldfusion?

ColdFusion is the hot way to create dynamic webpages that link to just about any database.

ColdFusion is a programming language based on standard HTML (Hyper Text Markup Language) that is used to write dynamic webpages. It lets you create pages on the fly that differ depending on user input, database lookups, time of day or whatever other criteria you dream up! ColdFusion pages consist of standard HTML tags such as , together with CFML (ColdFusion Markup Language) tags such as , and . ColdFusion was introduced by Allaire in 1996, acquired by Macromedia in a merger in April 2001, and acquired by Adobe in December 2005. It is currently in version 7.0.1, but the next version of the product (codenamed Scorpio) is already in development.

Creating an application with ColdFusion is as straightforward as creating a static Web site. However, in a ColdFusion application you can introduce an incredible range of functionality that is not available either in static Web sites or in traditional client/server applications. A ColdFusion application is very simply a collection of pages, similar to a static Web site. But unlike the pages in a static Web site, the pages in a ColdFusion application include the server-side ColdFusion Markup Language (CFML) in addition to HTML. CFML gives you the ability to control the behavior of your applications, integrate a wide range of server technologies, and dynamically generate the content that is returned to the Web browser.

When a page in a ColdFusion application is requested by a browser, it is automatically pre-processed by the ColdFusion Application Server. Based on the CFML in the page, the Application Server executes the application logic, interacts with other server technologies, and then dynamically generates an HTML page which is returned to the browser.


  • Coldfusion is a programming language
  • Coldfusion is an application server
  • Coldfusion is a middleware application for integrating the web and other tech. including database, e-mail and web services
  • Coldfusion is a tool for building dynamic web sites
Coldfusion Tutorial

1. Variables in Coldfusion

How to assign value to a variable in Coldfusion?


<cfset username = “gaurang”> // for string
<cfset password = 123456> // for number

Ex: This will define two variable named username and password and assign values to them


body tag start
<cfset username = “gaurang”>
<cfset password = 123456>
//body tag end


How to display the value of coldfusion variable?



<cfoutput>
#username#
#password#
</cfoutput>

Remember : <cfoutput> </cfoutput> tag must require to display value of variable.

Example: This will define two variables and assign values to them as well as also display the values.




//body tag start
<cfset username = “gaurang”>
<cfset password = 123456>

<cfoutput>
#username#
#password#
</cfoutput>
//body tag end
  • Use the same variable for multiple times
  • This example display uses of some string function available in coldfusion as well as how to use the value of single variable for many other variables
Example:

//body tag start
<cfset username = “gaurang”> // for string
<cfset Uppername = Ucase(username)> // for string
<cfset Lowername= Lcase(username)> // for string
<cfset Reversename= Reverse(username)> // for string
<cfset Lenname = Len(username)> // for string

<cfoutput>
Upercase = #Uppername#
Lower Case = #Lowername#
Reverse = #Reversename#
Number of Character = #Lenname#
</cfoutput>
//body tag end

When to use ‘#’ signs,

  • put ‘#’ to flag variables within a string of text.

<cfset firstname = “abc”>
<cfset lastname = “xyz”>

<cfset fullname = “#firstname#” “#lastname#”>
Result : abc xyz



  • if the string contains variables, pound signs would be necessary.

When not to use ‘#’ signs,

  • if variable is used inside some function,

    <cfset firstname = “abc”>
    <cfset lastname = “xyz”>

    Ex:
    <cfset UpperName = Ucase(#firstname#)> // Incorrect
    <cfset UpperName = Ucase(firstname)> // Correct

    Exception:
    <cfset #UpperName# = #Ucase(firstname)#>
    <cfoutput>
    #UpperName#
    </cfoutput>
    Result: ABC

2. Lists in Coldfusion.
Some of the basic features of List in Coldfusion.


  • Used to group together related information.
  • They are strings.
  • Delimiter is used to separate items within string.
Ex: comma delimited list of US state.

California, Texas, Florida, Michigan, New York

How to defined or create a List in Coldfusion?



<cfset friendlist = “gaurang, ankit, hiren, piyush, dipen, rahul, aakash, sunil, ankur, pratik, hemal,
jayesh, dhruv, hardik, tushar”>

List function in Coldfusion.


// display first element
<cfoutput>
First = #Listfirst(friendlist)#
</cfoutput>

// display last element
<cfoutput>
last = #Listlast(friendlist)#
</cfoutput>

// complete list
<cfoutput>
#friendlist#
</cfoutput>

//number of friends in list
<cfoutput>
Total friends = #Listlen(friendlist)#
</cfoutput>

// append new element
<cfoutput>
<cfset friendlist = #Listappend(friendlist, “vasant”)#
</cfoutput>

3 Arrays in Coldfusion.

They are like lists, store multiple values in a single variable. But it can contain more complex data including lists and other arrays. Unlike lists arrays support multiple dimensions

How to define or create an array in coldfusion?


<cfset fruitname = ArrayNew(2)> // create two- dimensional array

How to add to and display values of array?


<cfset fuitname[1][1] = “apple”> // first row, first column
<cfset fuitname[1][2] = “banana”> // first row, second column
<cfset fuitname[2][1] = “mango”> // second row, first column
<cfset fuitname[2][2] = “grapes”> // so on….

Display:
<cfoutput>
The first element of fruitname is #fruitname[1][1]# and second is #fruitname[1][2]#
</cfoutput>

Result:
The first element of fruitname is apple and second is banana.


4. Structures in Coldfusion

  • Most powerful and flexible data type in colfusion.
  • Provides a way to store data within data. No special dimension.
  • They like folders which can store either data or other folders which in turn can store data or other folders and so on.

How to create a structure in coldfusion?

<cfset cotanct = StructNew()>
<cfset contact.firstname = “gaurang”>
<cfset contact.lastname = “patel”>
<cfset contact.email = “gaurang.patel@yahoo.co.in”>


How to access data in structure?


<cfoutput>
Email :
#contact.firstname# #contact.lastname#
</cfoutput>

Result: Email : gaurang patel