ibs 685 week 6. update forms updating data the update process is as follows: –the user is...

106
IBS 685 Week 6

Post on 22-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

IBS 685

Week 6

Update Forms

Updating Data

• The update process is as follows:– The user is presented with a list of rows and

selects one row to update– A pre-filled form is presented to the user.– The user changes the values and submits the

form.– The action page processes the update.

Building an Update Action Page

• An update action page:– Contains <CFQUERY> tag with an SQL

UPDATE statement.– Should contain a message to the user, or

redirect them to another page.

Using <CFQUERY> with SQL UPDATE

Unless you use a “where” clause, all the rows will be updated.

Best Practices

• Always include a WHERE clause in an UPDATE statement to specify which row(s) to update.

• Do not allow users to update the primary key of a database record.

Pre-filling HTML Forms

• Pre filled form controls is particularly useful when forms are being used to update data.

• To pre-fill text controls, enter the initial value in the VALUE attribute of <INPUT> tag.

<INPUT Type=“text” NAME=“first_Name” Value=#Trim(q_getemployee.first_Name)#>

Client-Side Validation

• Client-side validation can only be accomplished with a scripting language, such as JavaScript.

• ColdFusion gives you a very powerful and simple way to implement client-side validation using <CFFORM> tag and its related tags.

• ColdFusion implements client-side validation by automatically generating JavaScript for you on the fly.

Using <CFFORM>

• In order to implement client-side validation you must use the <CFFORM> TAG.

• The method attribute of <CFFORM> defaults to “Post,” so that attribute may be omitted.

• The syntax for this tag is:

<cfform action=“form_action.cfm”>

……

</cfform>

Comparing <FORM> to <CFFORM>

<FORM ACTION=“login.cfm” method=“post”><Input type=“text” name=“login_name”><Input type=“submit” value=“Login”></FORM>

<CFFORM ACTION=“login.cfm”><CFInput type=“text” name=“login_name”><Input type=“submit” value=“Login”></CFFORM>

Using Required Attribute with CFINPUT

• Use <CFINPUT> to require entry of a value in a form control and display custom JavaScript alert messages:– Specify required attribute as “YES”– Provide a custom error message in the MESSAGE

attribute.

• CF will generate the JavaScript validation code that prevents form submission if the required fields was left blank.

• The following code validates that the login_name form control has a value upon submission.

<CFFORM action=“login.cfm” name=“login”><CFINPUT TYPE = “text” Name= “login_name”Required = “YES”Message = “Please specify login.”>INPUT TYPE = “Submit” Value=“Login”></CFFORM>

Using Required Attribute with CFINPUT

• When the user submits the form:– A JavaScript function is executed to perform a

validation check to ensure that the user provided an entry in the login_name field.

– If no entry has been provided, the function calls an error function, which, in turn calls JavaScript alert function to display an error message.

– The form is not submitted to the server if the login_name field is blank.

– See page 10-13

Using Required Attribute with CFINPUT

Using Validate Attribute

• Date of Birth: <CFINPUT TYPE = “text” Name= “dob”Required = “YES”Validate=“DATE”Message = “Valid Date of Birth Must Be

Specified”><BR>INPUT TYPE = “Submit” Value=“Register”></CFFORM>

• This code does the following:– The REQUIRED attribute instructs CF to generate JS

code to prevent form submission without values for the last_name, first_name and dob form controls

– The dob field uses the VALIDATE attribute to perform date validation. In this example, only valid date values are accepted.

– Each <CFINPUT> tag has a MESSAGE attribute that contains the error text to be displayed if validation fail.

Using Validate Attribute

• Data Types– Page 10-15– When you pass any of these data types to the

<CFINPUT> validate attribute, CF generates the appropriate JS Code.

– Besides Required, Validate and Message you can also use any of the standard <INPUT> tag attributes with <CFINPUT>, such as

• Value,• Size• Maxlength and• Checked

Using Validate Attribute

Displaying an Image using CFOUTPUT

1. Save images in a folder under wwwroot directory2. Create a database column and name it e.g. imagefilename

• Make sure that imagefilename column’s datatype is “Text”3. Create a query that selects the imagefilename column4. Create a img src tag where you want to display the image

• With you, is a new 5. Create a CFOUTPUT tag to display the image

• <cfoutput><img src=“#imagefilename#”alt=“image" border="0"> </cfoutput>

6. The alt tag can be dynamic too. You can output the definition of the image if you have the information in your database.

• <img

src="../Images/images/#getimage.imagename#" alt="" width="100" height="131" border="0">

• ../ = you can refer up one directory level for each instance of "../" you write in front of the path reference.

<CFMAIL>

• The structures of the email (such as the recipient list, the subject line and sender) is specified in attributes to the CFMAIL tag.

• The content of the message is placed between opening and closing CFMAIL tags.The critical attributes used in the CFMAIL tag are:To: specifies the email address of the recipientsFrom: Specifies the content of the From line of the messageSubject: Specifies the Subject line of the email

You don’t need to use cfoutput within cfmail tag, Your variables will be evaluated as if there were <cfoutput> tag in effect.

CFMAIL

<CFMAIL TO="recipient“ FROM="sender" SUBJECT="msg_subject" TYPE="msg_type" MIMEATTACH="path“>

• Before you can use the <CFMAIL> tag to send email messages, you need to specify a mail server in the CF Administrator.

CFMAIL Example

• <CFMAIL [email protected][email protected]=“A sample Coldfusion E-mail”This is my test message</CFMAIL>Type:Specifies the content type of the messageMIMEATTACH: Specifies the path and filename of a file

to be attached to outgoing email messageServer: Specifies an alternate SMTP mail server. By

default, the mail server specified in the CF administrator is used for sending outgoing messages

Generating Email from the Contents of a Form

<HTML>

<head>

<TITLE>Send a Greeting</TITLE>

</head>

<BODY>

<H1>Send a Greeting</H1>

<HR>

<P>Use the following form to send a greeting to a

friend by e-mail</P>

<FORM METHOD="POST" ACTION="sendgreeting.cfm">

Your Friend's E-mail Address:

<INPUT TYPE="text" NAME="to" SIZE=20><BR>

Your Name:

<INPUT TYPE="text" NAME="name" SIZE=20><BR>

<INPUT TYPE="SUBMIT" VALUE="Send">

</FORM>

</BODY>

</HTML>

<HTML>

<HEAD>

<TITLE>Sending Your Greeting</TITLE>

</HEAD>

<BODY>

<CFIF "Form.to" is not "">

<CFMAIL TO="#Form.to#"

FROM="[email protected]"

SUBJECT="A Greeting">Hi!

This is a quick, computer-generated greeting sent to

You courtesy of #Form.name# and the CFMAIL tag.

</CFMAIL>

<H1>Message Sent</H1>

<CFOUTPUT>

<P>Your message to #Form.to# has been sent </P>

</CFOUTPUT>

<CFELSE>

<H1>Oops </H1>

<P>You need to provide an E-mail address for the recipient. Hit the Back button to return to

the form and provide one. Thanks.</P>

</CFIF> </BODY></HTML>

Generating Email from the Contents of a Form

Using CFLOOP<cfquery datasource="emlak" name="getLocations">SELECT DISTINCT Location, ZipCode FROM Properties</cfquery><html><head><title>Locations Example</title></head><body><h3> List of Zip Codes and Locations with Properties for Sale</h3><ul><cfloop query="getLocations"><li> <cfoutput>#ZipCode#</cfoutput> - <cfoutput>#Location#</cfoutput></cfloop></ul></body></html>

• Optionally Query loop can have two additional attributes named STARTROW and ENDROW with values startrow_value and endrow_value.

• This allows you to restrict the output to a certain number of records in the record set of the query object.

CFLOOP<cfquery datasource="emlak" name="getLocations">SELECT DISTINCT Location, ZipCode FROM Properties</cfquery><html><head><title>Locations Example 2</title></head><body><h3> List of Zip Codes and Locations with Properties for Sale</h3><ul><cfloop query="getLocations" startrow="1" endrow=“2"><li> <cfoutput>#ZipCode#</cfoutput> - <cfoutput>#Location#</cfoutput></cfloop></ul></body></html>

• <CFINCLUDE template= /template_mapping/File.cfm>

• This would look up the /template_mapping CF mapping, replace it with C:\inetpub\wwwroot\includes and look for file.cfm in that directory.

Creating ColdFusion Mappings

Displaying an Image using CFOUTPUT

1. Save images in a folder under wwwroot directory2. Create a database column and name it e.g. imagefilename

• Make sure that imagefilename column’s datatype is “Text”3. Create a query that selects the imagefilename column4. Create a img src tag where you want to display the image

• With you, is a new 5. Create a CFOUTPUT tag to display the image

• <cfoutput><img src=“#imagefilename#”alt=“image" border="0"> </cfoutput>

6. The alt tag can be dynamic too. You can output the definition of the image if you have the information in your database.

• <img

src="../Images/images/#getimage.imagename#" alt="" width="100" height="131" border="0">

• ../ = you can refer up one directory level for each instance of "../" you write in front of the path reference.

<CFMAIL>

• The structures of the email (such as the recipient list, the subject line and sender) is specified in attributes to the CFMAIL tag.

• The content of the message is placed between opening and closing CFMAIL tags.The critical attributes used in the CFMAIL tag are:To: specifies the email address of the recipientsFrom: Specifies the content of the From line of the

messageSubject: Specifies the Subject line of the email

CFMAIL Example

• <CFMAIL [email protected][email protected]=“A sample Coldfusion E-mail”This is my test message</CFMAIL>Type:Specifies the content type of the messageMIMEATTACH: Specifies the path and filename of a file

to be attached to outgoing email messageServer: Specifies an alternate SMTP mail server. By

default, the mail server specified in the CF administrator is used for sending outgoing messages

Generating Email from the Contents of a Form

<HTML> <HTML> <TITLE>Send a Greeting</TITLE> </HTML> <BODY> <H1>Send a Greeting</H1> <HR> <P>Use the following form to send a greeting to a friend by e-mail</P> <FORM METHOD=POST ACTION="sendgreeting.cfm"> Your Friend's E-mail Address: <INPUT TYPE="text" NAME="to" SIZE=20><BR> Your Name: <INPUT TYPE="text" NAME="name" SIZE=20><BR> <INPUT TYPE=SUBMIT VALUE="Send"> </FORM> </BODY></HTML>

<HTML> <HEAD> <TITLE>Sending Your Greeting</TITLE> </HEAD> <BODY> <CFIF Form.to is not ""> <CFMAIL TO="#Form.to#" FROM="[email protected]" SUBJECT="A Greeting">Hi! This is a quick, computer-generated greeting sent to You courtesy of #Form.name# and the CFMAIL

tag. </CFMAIL> <H1>Message Sent</H1> <CFOUTPUT> <P>Your message to #Form.to# has been sent </P> </CFOUTPUT> <CFELSE> <H1>Oops </H1> <P>You need to provide an E-mail address for the recipient. Hit the Back button to return to the form and provide one. Thanks.</P> </CFIF> </BODY></HTML>

Generating Email from the Contents of a Form

The Web's Statelessness

• You will need to persist information across pages in order to:– Validate user authentication at login, and

maintain that authentication throughout the session

– Personalize the user’s experience– Maintain information about the user’s session

- for example, a shopping cart

Login Page

SELECT Count(*) AS Login_MatchFROM LoginsWHERE Login = '#Form.Login#'AND Password = '#Form.Pwd#‘

• The count function counts the number of records.• When you execute this select statement, it will

produce output that contains one column named login_match and one row where the value in the login_match field is the number of records in logins table

The Web's StatelessnessPage 528

• HTTP creates a new connection for every page request– Variables and flags set during one request

are not available for the next request

• Work around this problem by using:  – Cookies– Application framework– Session variables

Cookies

• Cookies are simple mechanism for asking a browser to remember something, such as a users favorite color or some type of ID number.The information is stored in the client machine’s memory

Client Variables

• Client variables are similar to cookies, except that the information is stored on the server, rather than on the client machine.

Session Variables

• Similar to client variables session variables are stored on the server. However instead of being stored physically they are simply maintained in the server’s RAM. Session variables are designed to hold temporary data, such as items in a shopping cart.

Feature Type UsageCookies A variable that is set and then stored on

the client machine for all subsequent requests.

Application

Framework

The ability to create variables for each page request by automatically including the application.cfm page

Session Variables A variable that is set for a particular session that persists for the life of the

browser session.

Securing Applications

• You need to:– Authenticate them on first access by giving them a login

page

– Allow access to an application for a predetermined session time or time without activity

– Secure each page to be sure they cannot bookmark a page and circumvent the login

Security Components

• Secure your Web pages by using the following security components:– Login page and login action page to authenticate users

against a database table of users– Application Framework to test for login on each page in

the application– Session variables to persist a logged in flag for each

page in the application

Web Application Framework

• The features all have to do with making all your CF templates for a particular site or project behave as if they were related to one another – that is to make them behave as a single application.

• These features are referred to as the

Web Application Framework

The Application Framework

• The application framework is enabled by the use of a special file, named Application.cfm

• This file is an ordinary CF Template.• The code in your application.cfm file will be automatically

included just before any of your application pages.• Same behaviour as you included the file using an ordinary <cfinclude>

tag at the top of every page.

• You cant visit an application.cfm file directly.– You will receive an error message from the browser.

• This reserved file name, when it exists, is always included at the top of every CF page request.

Application.cfm File

• CF looks for an Application.cfm file in the directory of the called page.– If not found in the current directory, CF will

continue to search the directory structure for a file named Application.cfm

– If found, the Application.cfm file will be included at the top of the page

– If not found, CF continues processing the page without it.

Application.cfm

• CF will look up to the drive root to find Application.cfm. Only one application.cfm is ever processed for a page.– Page 11-6

• The /Marketing directory has an Application.cfm file, so any page in that directory or below will include this file.

• Since the /Sales directory does not have an application.cfm file, CF looks up the directory structure to find it. – CF locates the first one, here in the \wwwroot

directory, and includes the file.

Application.cfm

A basic Application.cfm Template

<!---Any variables set here can be used by all our pages--->

<CFSET datasource = “OWS”>

<CFSET CompanyName=“Orange Whip Studios”>

<!---Display our site header at top of every page--->

<cfinclude template=“Siteheader.cfm”>

Using Application.cfm

<HTML>

<HEAD>

<TITLE>

<cfquery name=getemp datasource=#Datasource#>

<cfoutput> #CompanyName#</cfoutput>

</HEAD>

</HTML>

OnRequestEnd.cfm

• Automatically included at the very end of every page request, rather than at the beginning.

• This file cannot be visited directly• CF looks for OnrequestEnd.cfm in the same

folder as application.cfm• Place OnrequestEnd.cfm in the same location in

which your Application.cfm is sitting.

<!---Display our site footer at bottom of everypage--->

<cfinclude template = “Sitefooter.cfm”>

OnRequestEnd.cfm

Another Example

<cfoutput>

<font size = “1” face=“sans-serif” color=“silver”>

<p>(c) #year(Now())# #CompanyName#.

All rights reserved.<br>

</cfoutput>

</body>

</html>

Overriding Application.cfm Inclusion

• You cannot stop CF from including the closest Application.cfm file.

• You can however override an application.cfm file in a directory above a file by including another application.cfm file in the current directory.

• An Application.cfm file cannot be empty. You must have at least a space in the file in order to keep from getting an error.

• Most developers will put a comment in the file to tell you that it is a dummy application.cfm file that will override one in a directory above.

Application Variables

• Application variables are shared between all pages in your application.

• Because they are not maintained separately for each user, they don’t go far in helping you create a personalized site experience.

• The problem is that the web itself creates no short term memory for remembering the contents of a shopping carts and other types of choices users make during a visit.

• You need something to provide that short term memory for you.

Solutions Provided by ColdFusion

• CF provides three types of variables that help you maintain the state of a users visit from page to page and between visits.

– Cookies– Client Variables – Session Variables

HTTP Cookie Variables

• Cookies are simple variables that can be stored on a client machine.

• Browsers store cookies in a physical file or files on the client machine.

• Once the browser has a cookie set, each and every HTTP request will retrieve all cookies for the requested web server domain.

• If the user requests a page from the Macromedia domain, all cookies for that domain would be sent in the HTTP header to the web server.

• Once the browser send the cookies via the HTTP header, CF has access to all of these cookies at runtime.

HTTP Cookie Variables

• Cookies are:– Domain specific-set and retrieved for specific

servers.– Sent to the Web server with every HTTP

request– Persistent-they remain stored in the browser

until expired or deleted– Limited to 20 per domain and 4 K worth of

information.

Cookie Uses

• Cookies are used to obtain information about a user between and within browser sessions. Use of cookies include:– Storing a unique identifier as a cookie, so that

information such as shopping cart data is identified to the browser session.

– Storing a session information, such as a flag that they are logged in until the browser is closed.

– Storing user preferences, so they might return to the site and have the same look and feel.

Making Cookies

• CF allows you to create cookie by using <CFCOOKIE> tag.

• The most common reason for using <CFCOOKIE> is to control how long the cookie will live before before it expires.

• To set a cookie with user_ID with value of 2344:– <CFCOOKIE Name= “USER_ID” value=“2344”

Expires = “100”>

Cookie Types

• There are two types of cookies you can create:• Persistent cookies• Session cookies

• Both can be created using the <CFCOOKIE> tag• Differentiated by the use of the EXPIRES

attribute.

Persistent vs. Session Cookies

• Persistent Cookies:– EXPIRES attribute determines when the cookie

gets deleted from the browser machine:•EXPIRES = "n" •EXPIRES = "date" •EXPIRES = "never" •EXPIRES = "now"

Session Cookies

• Created by omitting the EXPIRES attribute from the <CFCOOKIE> tag

• Only valid until all the browser sessions on that client machine are closed

• Use this value when you only want to track the user for the current session

• Destroyed when the browser sessions close, and are never stored in a file on the browser machine

Accessing Cookies

• Since HTTP specifies that all cookies be automatically sent to the requesting Web server domain, you do not need to fetch them.

• You would access a cookie simply by using it and prefixing it with the Cookie prefix.– The user_ID is:– <cfoutput>#cookie.user_ID# </cfoutput>

• Because cookies are physical files stored on the browser computer that can be deleted at will, you should always test for the existence of cookies prior to use.– Test for existence using the IsDefined () function

<cfif isdefined (cookie.user_ID)>

The user ID is:

<cfoutput>#cookie.user_ID# </cfoutput>

</cfif>

Accessing Cookies

• You have only been able to pass information between pages using:– URL variables passed on the hyperlink to the linked

page– Form variables passed in the form scope to an action

page

• There are other types of variables that allow you to store information once, and then share it amongst an application, a session or the entire server.

Persistent State Variables

Persistent State Variables

• Variables that allow you to store information once, and then share it in an application, a session or the entire server. – Server– Application– Session– Client– Request

• We will focus on Session and Request scopes.

• Session Scope: Variables are available for all page requests from a specific browser until the session expires.

• Request Scope: Variables are available to a single page request, including any custom tag calls made within the page.

Request Variables

• Request variables are similar to local variables in that they are only stored for the length of the page request.

• DSN Example• Request scope variables are available to the

entire request-the requested page and all custom tags called within it.

• Therefore, you could instead set the DSN as a request scope variable and it will now be available for the entire request.

Session Variables

• Session variables are:– Stored in the Web server's memory – Lost when the Web server is restarted – Used for single site visit

• Session variables are not stored physically in the server’s or in the database. Instead they are stored in the servers RAM

• In order to use Session variables, you will need to:1.Check the ColdFusion Administrator for Session

settings 2.Enable Session variables within your Application.cfm file3.Set Session variables in your ColdFusion pages

ColdFusion Administrator Settings

• Session variables must be enabled before use. • Check the following settings in the ColdFusion

Administrator to:1. Make sure that Session variables have not been

disabled

2. Set/reset the Session variables default and maximum timeout settings

ColdFusion Administrator Settings 11-22

• Found in the ColdFusion Administrator in the Server Settings section under Memory Variables

Enabling Session Variables

• Enable session variables by using <CFAPPLICATION> tag.• This tag is always included in Application.cfm file.• Enable session variables in the Application.cfm file:

<CFAPPLICATION name="CoffeeValley" sessionmanagement="Yes"sessiontimeout=#CreateTimeSpan("0", ”1", “0”, "0")#>

• Enables session variables and sets expiration to 1 hour after last browser activity for each session

The maximum timeout default in the ColdFusion Administrator is 20 minutes. Change this value in order for the above tag to allow timeout at 1 hour.

• After you have enabled session variables using <CFAPPLICATION>, you can start using them in your code.

• You can set and use session variables by simply using the Session prefix in front of a variable’s name.

Session Variable Process

1. The first time a browser requests a page from ColdFusion, it will encounter the <CFAPPLICATION> tag. This is always placed in an Application.cfm file.

2. ColdFusion will generate a unique identifier for the browser. The unique ID is made up of two values: CFID and CFTOKEN.

3. Two cookies are created and sent to the browser: CFID and CFTOKEN.

4. These two values are also stored in the Web server’s memory within the application. This is the link between the Web server and the browser session.

1. The first time a browser requests a page from ColdFusion, it will encounter the <CFAPPLICATION> tag. This is always placed in an Application.cfm file.

2. ColdFusion will generate a unique identifier for the browser. The unique ID is made up of two values: CFID and CFTOKEN.

3. Two cookies are created and sent to the browser: CFID and CFTOKEN.

4. These two values are also stored in the Web server’s memory within the application. This is the link between the Web server and the browser session.

Creating Session Variables

• Session variables are stored in server memory with the matching CFID and CFTOKEN values

• Each session will have a separate set of variables• Once the association between the browser and

the session is made, session variables can be created using the <CFSET> tag

• The Session. prefix is required<CFSET Session.BGColor="red">

Creating Session Variables

• Session variables are stored in server memory with the matching CFID and CFTOKEN values

• Each session will have a separate set of variables

• Once the association between the browser and the session is made, session variables can be created using the <CFSET> tag

• The Session. prefix is required

<CFSET Session.BGColor="red">

Disabled Cookies

• If a browser has disabled the receipt of cookies, your ColdFusion application will need to pass the client information for every page request

• Append CFID and CFTOKEN on URL• Pass CFID and CFTOKEN in hidden form controls• Use ADDTOKEN=“Yes” to CFLOCATION tag

Locking Shared Variables

• Application and session (as well as server) scope variables are shared– These variables can be set and retrieved at the same time– Setting/getting values from the same place in memory at the

same time can cause corruption, and can lead to system failure

• Session variables can collide if:– The user hits Refresh in their browser while it's already

processing a Session variable– A Session variable is used within a frameset

• Every read and write of shared memory values requires the use of the <CFLOCK> tag to ensure memory integrity

Renaming Query Columns(p 982)

• For each column you specify in the SELECT statement, a CF variable is created. These variables are named the same as the column in the database.

• However you may rename these columns using SQL aliases.

<CFQUERY name = “q_getdist”

Datasource=“fasttrack_lab”>

Select distributor ID AS DID, Distributor_Name

From Distributor

Order By Distributor.Distributor_ID

</CFQUERY>

Renaming Query Columns

• This statement will return a result set named “q_getDist” with two columns:– DID and Distributor_Name– The AS keyword is used to rename the column at

runtime.– To print the values:<cfoutput query =“q_getdist”>#q_getdist.DID## q_getdist.Distributor_name#</cfoutput>

Renaming Query Columns

• SQL aliases are used to rename columns in a select statement. They are used to:– Rename columns that might be duplicate

within a select statement – Shorten names, requiring less typing– Give a name to aggregate values

• Select count(*) as rowcount….

Renaming Query Columns

User Defined Functions

• New to CF 5.0, user defined functions (abbreviated as UDF’s) allow developers to differentiate between reusable processes (in custom tags) and reusable functions (in UDF’s)

• CF offers many built-in functions that offer many utilities within encapsulated functions.

• Now you can create your own functions

• A UDF can take in arguments and return values.• Allaire Developers Exchange also has a set of

growing UDFs • The generic syntax for calling a function is:• Function_name(argument1, argument2…)• Since the argument names are not specified in

the call of the function, the order in which you list the arguments is important.

User Defined Functions

Calling UDF’s

• The following example of calling a function calls the amortization function and passes in a few arguments. The return value for the function will be displayed to the page.

<CFOUTPUT>

Amortization #(“140000”, “7” “360”)#

</CFOUTPUT>

Walkthrough 5-4

• Calling a UDF

• http://devex.macromedia.com/developer/gallery/index.cfm

Displaying Image

• Movies7.cfm and details3.cfm

Using Looping<CFLOOP> (p-246)

• Loops are another fundamental language element

• Loops do just that-They loop

• Loops provide a mechanism with which to repeat tasks

Types of Loops

• Index Loops *

• List Loops *

• Conditional Loops

• Query Loops

• Collection Loops

The Index Loop

• One of the most frequently used• Syntax<CFLOOP INDEX="parameter_name" FROM="beginning_value" TO="ending_value" STEP="increment">

HTML or CFML code to execute   ... </CFLOOP>

<CFLOOP INDEX=“i" FROM="1" TO="5"> <CFOUTPUT><LI>Item#i# </LI></CFOUTPUT>

  </CFLOOP>

List Loop

• Syntax<CFLOOP INDEX="index_name" LIST="list_items"

DELIMITERS="item_delimiter"> </CFLOOP>

<CFLOOP INDEX="ListElement" LIST=“Richard,Teann,Lu,Jose, Michael, John"> <CFOUTPUT>#ListElement#</CFOUTPUT><BR> </CFLOOP>

Looping Over a Query

• A loop over a query repeats for every record in the query record set. The CFLOOP results are just like a CFOUTPUT. During each iteration of the loop, the columns of the current row will be available for output.

Syntax

<CFLOOP QUERY="query_name" STARTROW="row_num" ENDROW="row_num">

<CFLOOP Query>

<CFQUERY NAME="MessageRecords" DATASOURCE="cfsnippets"> SELECT * FROM Messages </CFQUERY> <CFLOOP QUERY="MessageRecords">

<CFOUTPUT>#Message_ID#</CFOUTPUT><BR> </CFLOOP>

<CFLOOP Query>

CFLOOP also provides iteration over a recordset with dynamic starting and stopping points. Thus you can begin at the tenth row in a query and end at the twentieth. This mechanism provides a simple means to get the next n sets of records from a query.

The following example loops from the tenth through the twentieth record returned by "MyQuery ":

<CFSET Start=10> <CFSET End=20> <CFLOOP QUERY="MyQuery" STARTROW="#Start#"

ENDROW="#End#"> <CFOUTPUT>#MyQuery.MyColName#</CFOUTPUT><BR> </CFLOOP>

Introducing Custom Tags

• CF developers can extend the CF language by creating their own tags.

• These are referred to as either custom tags or CFXs

CFML Custom Tags

• CFML custom tags are bits of code or functionality that are written with the CFML language and then called from within other CFML templates.

• Since CFML templates are reusable, you also gain the same benefits that you have with the <CFINCLUDE> tag, like code reuse and easier maintenance

Allaire’s Developers Exchange

• Allaire’s Developers Exchange is an online repository of custom tags created by CF developers.

• It is a good idea to check before developing your own.

Writing Your First Custom Tag (p614)

• Custom tag resolution– Save the file as helloworld.cfm in – Current directory of the calling page– C:\cfusion\customtags– And view it as <cf_helloworld>

Passing Attributes

• Custom tags may be created to accept parameters, called attributes.

• When using custom tags, you will need to know what parameters are accepted into the tag.

• To pass attributes into a custom tag, you simply append attribute = value pairs at the end of the custom tag– <CF_FOO attribute1=“value1” attribute2=“value2”>

Custom Tag<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html><head>

<title>Calling Custom Tags</title></head>

<body>

<CF_ImageRollover SRC1="allaire.gif" SRC2="mm.gif" HREF="http://www.macromedia.com/">

</body></html>

SQL is Not Typeless

Text field variables must be surrounded with single quotes.

Numeric field variables values are not surrounded by single quote