Summary of Contents for MACROMEDIA COLFUSION MX 7-GETTING STARTED BUILDING COLDFUSION MX
Page 1
COLDFUSION MX 7 ® Getting Started Building ColdFusion MX Applications...
Page 2
Other product names, logos, designs, titles, words, or phrases mentioned within this publication may be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in certain jurisdictions including internationally.
CONTENTS ........... 7 INTRODUCTION PART I: Welcome to ColdFusion CHAPTER 1: Introducing ColdFusion MX...
Page 4
CHAPTER 5: Lesson 2: Configuring Your Development Environment ..49 Exercise 1: Verifying the tutorial file structure ......49 Exercise 2: Setting up your development environment.
Page 5
CHAPTER 11: Lesson 8: Implementing Browsing and Searching ... . 123 Exercise 1: Enabling users to browse trip details ......123 Exercise 2: Determining actions based on which button a user clicks.
If you did not install the ColdFusion MX sample applications, you can download the tutorial files from the ColdFusion Support center on the Macromedia website. About Macromedia ColdFusion MX 7 documentation The ColdFusion MX 7 documentation is designed to provide support for the complete spectrum of participants.
Page 8
Document Format (PDF) files. Go to the documentation home page for ColdFusion MX on the Macromedia website: www.macromedia.com. In addition, you can view the documentation in LiveDocs, which lets you add comments to pages and view the latest comments added by Macromedia, by going to www.macromedia.com/go/livedocs_cfmx7docs.
PART I Welcome to ColdFusion Part I provides an introduction to Macromedia ColdFusion MX 7. It defines ColdFusion MX 7 and provides an overview of the ColdFusion Markup Language (CFML). It also provides generic database concepts. The following chapters are included in Part I: Chapter 1: Introducing ColdFusion MX .
CHAPTER 1 Introducing ColdFusion MX This chapter introduces the core technologies that are the foundation for Macromedia ColdFusion MX. In addition, it introduces the basic concepts about ColdFusion MX, how it works, and the various components that comprise it. Contents About ColdFusion MX .
The ColdFusion Markup Language ColdFusion Markup Language (CFML) is a tag-based language similar to HTML that uses special tags and functions. With CFML, you can enhance your standard HTML files with database commands, conditional operators, and high-level formatting functions, and rapidly produce easy- to-maintain web applications.
Development tools You can code your ColdFusion application with NotePad or any HTML editor; however, Macromedia recommends that you build your applications using Macromedia Dreamweaver MX. Dreamweaver MX offers features and wizards that enhance ColdFusion development. For more information about Dreamweaver MX, see Chapter 5, “Lesson 2: Configuring Your...
CHAPTER 2 CFML Basics This chapter introduces the basic elements of CFML, including how to create Macromedia ColdFusion pages, and use variables, functions, conditional processing, and form processing. Contents Working with ColdFusion pages ..........15 About CFML elements .
Page 16
The best choice for creating ColdFusion pages is Macromedia Dreamweaver MX. Dreamweaver MX includes many CFML features for building applications, such as rapid visual development, robust CFML editing, and integrated debugging. Dreamweaver MX also includes a copy of HomeSite+ for users who are familiar with developing their application code using ColdFusion Studio or HomeSite 5.
Page 17
Saving your ColdFusion page In order for the ColdFusion server to process the page, you must save the ColdFusion page on a computer where the ColdFusion MX is installed. If you are creating your pages on a local server (on which ColdFusion is running), you can save the pages locally; if you are using a remote server, you must save your pages on that server.
The following figure shows the cfpage.cfm page in the browser: Do the following tasks: View the source code that was returned to the browser. In most browsers, you can view the source by right-clicking on the page, and then selecting View Source. Compare the browser source code with the source code that appears in your editor.
Page 19
Most often the end tag encloses the tag name in brackets and includes a forward slash (/), like this: </tagname> The information processed by ColdFusion is placed between the start and end tag, like this: <tagname> info to be processed ... </tagname>...
Page 20
Functions and number signs You use number signs (#) with functions to display the results of a function on the page. Number signs tell the ColdFusion server to evaluate the content between the number signs and display the value, for example: <cfoutput>...
Page 21
Using functions on values Usually, a function performs an operation on a value, and the value can include the value of a variable. For example, to format the value of a variable that contains a value in dollars, the code to write this statement might look like this: #DollarFormat(price)# function returns a value as a string and formats that value with two decimal...
Page 22
In the following examples, the variables are assigned a string literal value. All string literal values are surrounded by double-quotation marks. <cfset my_first_name = "Kaleigh"> <cfset my_last_name = "Smith"> In the next example, ColdFusion uses the values of the my_first_name my_last_name variables to set the value for the variable in the last line of code.
Displaying variable output Output is what remains after the ColdFusion server processes the CFML tags on a page. Usually the output has two parts: • Information that the user sees (for example, a confirmation message) • Information that is stored by the server as a result of processing (for example, user input collected from a form) One of the tags that ColdFusion provides to display output is the tag.
Page 24
Building expressions In ColdFusion, you build expressions as you need them. The expressions can include simple elements, such as the expressions shown previously, or they can include complex elements, such as arithmetic functions, strings, and decision operators. (You build some complex expressions in Part II of this manual.) As mentioned, it is important that elements are identified properly in your expression so that ColdFusion processes them as expected, and you avoid unnecessary errors.
Page 25
For more information and examples on using number signs in expressions, see ColdFusion MX Developer’s Guide. Specifying quotation marks around values When you assign literal values to variables, you must surround the literal value with single- or double-quotation marks. ColdFusion interprets the content between the quotation marks as a literal value and assigns that value to the variable;...
Page 26
The following table lists the unsupported logical operators and their equivalent ColdFusion operators: Unsupported Equivalent ColdFusion Description logical operator decision operator IS, EQUAL, EQ Tests for equality. < LT, LESS THAN Tests for less than. <= LTE, LE, Tests for less than or equal to. LESS THAN OR EQUAL TO >...
String operator The following table describes the one ColdFusion string operator that is a concatenation operator: Operator Description & Concatenates strings. About conditional processing So far, all the coding examples shown in this chapter are considered linear coding examples. Linear code is when ColdFusion executes code starting with the first line on the page, and processes every line in order.
Using the cfelseif tag to evaluate multiple expressions To evaluate multiple expressions in a statement, you can use tags in cfif cfelseif cfelse your statement; for example: <cfif expression 1> HTML and CFML tags executed if expression 1 is True. <cfelseif expression 2>...
Page 29
When a user submits a form, the form values are stored in form variables and sent to the action page for processing. The following figure shows the relationship between the form page and action page: Form page Name E-mail Submit form.var1=value1 form.var2=value2 The action page contains...
Commenting your code As in other programming languages, it is important to include comments in your code. You should comment your code for the following reasons: • Commented code is easier to debug than code that is not commented. • If you describe the code on the page, it is easier to make modifications.
CHAPTER 3 Database Fundamentals This chapter provides a quick overview of relational database concepts and terms. It describes what a database is and how it is organized. It also discusses the Structured Query Language (SQL) that you use to interact with databases. Contents About database basics.
Page 32
What is a relational database? A relational database is a structured collection of information that is related to a particular subject or purpose, such as an inventory database or a human resources database. You use databases to manage information. Information, such as product name, cost, and on-hand inventory, is stored in a database.
Page 33
About relational tables In a database, you can organize data in multiple tables. For example, if you manage a database for the Human Resources department, you might have one table that lists all the information about employees and another table that lists all the departments: You have multiple departments for employees, but you would not store the information about the departments in every employee row for the following reasons: •...
About SQL SQL (Structured Query Language) is a language that lets you communicate with databases. For example, you can use SQL to retrieve data from a database, add data to a database, delete or update records in a database, change columns in multiple rows, add columns to tables, and add and delete tables.
Page 35
Using the SQL WHERE clause to limit the rows returned To conditionally select data from a table, you can add a WHERE clause to the SELECT statement, which results in the following syntax: SELECT column_name FROM table_name WHERE column condition value With the WHERE clause, you can use any of the following operators: Operator Description...
The result of the preceding SQL statement contains the following data: LastName FirstName Brown Marie Note: The preceding SQL SELECT examples use single-quotation marks around the value. SQL uses single-quotation marks around text values. Most database systems also accept double- quotation marks.
Page 37
Writing SQL and CFML statements to interact with a data source After ColdFusion makes a connection to the data source, you can interact with that database by using SQL and ColdFusion. To interact with an established data source, you must include SQL statements in your CFML statements;...
Page 39
PART II Building a ColdFusion Application Part II provides a tutorial that steps you through building a sample Macromedia ColdFusion application. It consists of the following lessons: Lesson 1: Preparing to Build the Sample Application ....... . 41 Lesson 2: Configuring Your Development Environment .
This tutorial guides you through the process of building a simple Macromedia ColdFusion web application. By the end of the tutorial, you will be familiar with how to use Macromedia ColdFusion MX 7 to query and update a database, validate data, generate a report, and require user authentication.
Step Description Design the database for your application by exploring the database tables that will store the trip information. Develop the ColdFusion application pages. The following sections explore an overview of each of these application development steps. Exercise 1: Determining the application functional requirements Before you can build the sample application, you must understand the functional requirements that influence its design.
Exercise 2: Determining the data requirements Prior to creating the application pages to capture trip information, you must determine what type of data is required about each trip. For the example in this tutorial, the Compass Travel trip coordinator must maintain the following information about each trip: •...
Page 44
If you had to create the Compass Travel database, you would create a table named trips to store the information that you plan to collect about each trip. The table would look something like the following table: Recognizing the data types Each field in the Trips table has a data type attribute that describes the type of data that can be stored in the column.
Page 45
Establishing a relationship between the two tables When the user selects an event type from the list obtained from reading the eventtypes table, the correct event type must be saved to the trips table with all the other trip-related data. The application could store the eventType (for example, mountain climbing) itself into the eventType column in the trips table.
Exercise 4: Developing the sample application Using the application functional requirements and the database that is provided for this tutorial, you are ready to use ColdFusion to develop the Trip Maintenance application. The remaining lessons in the tutorial step you through the process of constructing this application. When you are done, the main page for the Trip Maintenance application will appear as follows: The main application page is where users will come to view information about trips and to navigate to other ColdFusion pages to add, edit, or search for new trips.
Page 47
• Implement browsing and searching (“Lesson 8: Implementing Browsing and Searching” on page 123). • Enable database maintenance (“Lesson 9: Enabling Database Maintenance” on page 129). • Restrict access to the Compass Travel application by requiring user authentication (“Lesson 10: Restricting Access to ColdFusion Applications”...
Page 48
Dreamweaver Extensions described in this tutorial, you must use Dreamweaver MX 2004. However, you can use Macromedia HomeSite+, ColdFusion Studio, any text editor, or IDE, and copy and paste the code that the Dreamweaver Extensions create. In the exercises in this tutorial, the term editor means Dreamweaver MX 2004, HomeSite+, ColdFusion Studio, or any text editor or IDE of your choice.
In this lesson, you set up your development environment for the tutorial. This lesson describes the tutorial file structure, and how to configure the database connection and debugging options. Additionally, it provides an overview of using Macromedia Dreamweaver MX for Macromedia ColdFusion development.
Exercise 2: Setting up your development environment If you are running ColdFusion in a Windows environment, Macromedia recommends that you use Macromedia Dreamweaver MX for ColdFusion development; however, if you are running ColdFusion in a UNIX environment, you should use the text editor that you prefer. Although...
Page 51
With Dreamweaver MX, you can author and test your application code from a local or remote client. You can save your code directly to the server computer where ColdFusion is installed. The following sections provide an overview of Dreamweaver MX, and information on how to configure Dreamweaver MX for ColdFusion development.
Exercise 3: Configuring a database connection One of the most commonly used and most powerful features of ColdFusion is the ability to connect to and manipulate data from a wide variety of databases. Like most ColdFusion developers, you will probably use this capability often. To be able to connect to a database, you must create a a data source in ColdFusion.
Page 53
To access the ColdFusion MX 7 Administrator: • Open a browser and go to one of the following URLs: External web server users: http://localhost/CFIDE/administrator Built-in web server users: http://localhost:8500/CFIDE/administrator J2EE server users: http://localhost:portnumber/CFIDE/administrator. If you installed ColdFusion Enterprise Edition with JRun, the default HTTP port is 8300. Note: If you are accessing the ColdFusion MX Administrator from a remote client, you must replace localhost with the host name or IP address of the computer where ColdFusion MX is installed.
Page 54
To define the sample PointBase database file: In the ColdFusion MX Administrator, select Data & Services > Data Sources. The Add New Data Source dialog box appears. Specify the following: Field Action Data Source name Specify the name CompassTravel. text box Note: Ensure that the name of the data source file does not contain any spaces.
Click Verify All Connections to ensure that ColdFusion can access this file. OK appears in the Status column for successful connections. If the connection to the compass travel data source fails, do the following: Verify that the name of the data source file does not contain a space. If it does contain a space, delete the data source from the Connected Data Source dialog box.
Page 56
The location of the debugging information or the type of debugging data shown varies, depending on the options that you enable on the Debugging page in the ColdFusion MX Administrator. In the following example, the debugging output includes general information about the ColdFusion server, the execution time of the application, and variable information: The following figure shows an example of how debugging information can appear when appended to the bottom of a page in a browser:...
Sending debugging information to remote clients If you are using a remote client to perform the tutorial in this book, you must specify your IP address to receive debugging information. If you are working on a local client (the computer where ColdFusion is installed), you do not need to do this.
Page 58
Chapter 5: Lesson 2: Configuring Your Development Environment...
CHAPTER 6 Lesson 3: Retrieving Data In this lesson, you begin the construction of a Macromedia ColdFusion web application for the fictitious company, Compass Travel. The exercises in this lesson introduce you to the process of retrieving data from the Compass Travel relational database.
Exercise 1: About the trip list As you recall from “Lesson 1: Preparing to Build the Sample Application” on page 41, one of the requirements for the Trip Maintenance application is the ability to generate trip listings. To help Compass Travel agents take trip reservations by telephone and in person, the trip coordinator maintains a list of current trip offerings.
Exercise 2: Retrieving the information for the trip list Relational database management systems process SQL instructions sent to them from various applications. ColdFusion sends SQL statements to database managers to manipulate data. ColdFusion needs a way to know to which database manager to send a specific SQL string for evaluation.
Reviewing the code The following table describes the code used to build the query: Code Explanation <cfquery name="TripList" ColdFusion query named TripList. Submits any SQL statement datasource="CompassTravel"> between the start and end tags to the data source cfquery specified in the attribute.
<body> <h1>Trip List</h1> <cfoutput query="TripList">#tripName#<br></cfoutput> </body> </html> Save the file as triplisting.cfm in the my_app directory. View the triplisting.cfm page in a browser. The page lists all the trip names retrieved from the Compass Travel database. Reviewing the code The following table describes the code used to display the query result set: Code Explanation <cfoutput query="TripResult">...
Page 64
To create the CFC file: Create a directory named components as a subdirectory of the my_app directory. Open a new blank file. Note: If you are using Dreamweaver, select Dynamic page in the Category list, and select ColdFusion Component in the Dynamic Page list. Enter the following code, or do the steps listed in the “Let Dreamweaver do it”...
Page 65
Copying the query to the CFC To copy the query to the CFC, you copy the CFML to the CFC, between the opening and closing tags. cffunction To copy the query to the CFC: Highlight the following code on the triplisting.cfm page: <cfquery name="TripList"...
Let Dreamweaver do it Dreamweaver lets you invoke a method in a CFC without having to write the code. To invoke the method using Dreamweaver: Click the Components tab in the Application panel. Click the + button next to cfdocs.getting_started.my_app.components. Click the + button next to gettrips.
Page 67
output="false"> <cfquery name="budgetTrips" datasource="CompassTravel"> SELECT tripName, departureDate, returnDate, price FROM trips WHERE price <= 1500 ORDER BY tripName </cfquery> <cfreturn budgetTrips> </cffunction> Save the file. Let Dreamweaver do it You can use the Dreamweaver Extensions to create a CFC query and invoke the method that contains the query from the triplisting.cfm page.
Page 68
Invoking the new method To use the new query, you invoke the method that contains the query. To invoke the new method with the enhanced query: Open the triplisting.cfm file. Modify the following code, or do the steps listed in the “Let Dreamweaver do it”...
Save both the triplisting.cfm file and the gettrips.cfc file. View the triplisting.cfm page in a browser and verify that all the new requirements were met. The revised TripListing.cfm page looks like this: The dates and prices in the preceding listing are not formatted. In “Lesson 6: Creating a Main Application Page”...
CHAPTER 7 Lesson 4: Building Dynamic Queries In this lesson, you develop a search form to allow users to select the information to retrieve, and then display, the search results. This lesson contains the following exercises: Exercise 1: Creating the trip search form ......... 71 Exercise 2: Building a query that uses dynamic SQL .
Page 72
A better solution is to provide an interface for the user to specify the search criteria. The purpose of the Trip search form is to enable Compass Travel employees to search and view brief details about existing trips on their website. The completed form should appear as follows: Designing the search criteria page When designing the search criteria page, it is a good idea to develop a list of possible queries that the user might issue when searching for the records.
Page 73
In later exercises, you will reference these columns when you build the SQL SELECT statement for the in the search action page. cfquery Understanding search query operators Now that you have decided which columns can be queried (tripLocation, departureDate, and price), you can build a simple form that lets the user enter values for each of these fields.
</form> </body> </html> Save the file as tripsearchform.cfm in the my_app directory. Reviewing the code The following table describes the search criteria code and its function: Code Explanation Identifies tripsearchresult.cfm as the search <form action="tripsearchresult.cfm" method="post"> action page. Results of user entry are passed to the search action page.
Page 76
The action page invokes a method that builds the WHERE clause so that the SQL SELECT statement retrieves the information that the user requests. Then, the action page displays an HTML table with the results of the user query using the block.
Page 77
<cfset WhereClause = WhereClause & " AND tripLocation like '" & form.tripLocationValue & "%'" > </cfif> When you test for a string column within the WHERE clause of the SQL SELECT statement, you must enclose the test value in quotation marks. When you use a variable to construct a WHERE clause, you must preserve the quotation marks so that the database server does not return an error.
Page 78
</cfquery> <cfreturn TripResult> </cffunction> Add the highlighted code to the block to use the dynamically built WHERE clause in cfquery the query: <cfquery name="TripResult" datasource="CompassTravel"> SELECT tripID, tripName, tripLocation, departureDate, returnDate, price FROM trips WHERE #PreserveSingleQuotes(WhereClause)# </cfquery> Save the file. Let Dreamweaver do it You can use the Dreamweaver Extensions to create the CFC query.
Exercise 3: Constructing the initial Trip Search Results page After the user enters the search criteria and submits the form, the results are posted to the Trip Search Results page, as the following figure shows: The logic contained in the search results page, also known as the action page, invokes the CFC method that builds the SQL SELECT statement contained in a tag by using cfquery...
Page 80
</td> </tr> <cfoutput query="TripResult"> <tr> <td>#tripName# </td> <td>#tripLocation# </td> <td>#departureDate# </td> <td>#returnDate# </td> <td>#price# </td> </tr> </cfoutput> </table> </body> </html> Save the file. Let Dreamweaver do it As you have in previous exercises, you can let Dreamweaver generate the code to invoke the method.
Code Explanation <cfif Form.tripLocationValue GT ""> tag tests to see if the user entered anything The cfif in the Value input field for tripLocation criterion. SQL query to execute. The SELECT tripName, tripLocation, PreserveSingleQuotes departureDate, returnDate, price, tripID function ensures that quotation marks are passed to FROM trips the database server as intended.
Verify that the other criteria (departure date and price) are not taken into consideration yet as follows: Click the Back button in the browser to return to the Trip Search page. In the Departure Date drop-down list box, select Before, enter 1/1/1900 as the date, and select Smaller Than 0 for the price.
To build the WHERE subclause, enter the following code after the code you entered in price the previous step. <!--- Build subclause for price---> <cfif Form.priceValue GT ""> <cfif Form.priceOperator EQ "EQUALS"> <cfset WhereClause = WhereClause & " and price = " & form.priceValue> <cfelseif Form.priceOperator EQ "GREATER">...
Page 84
Chapter 7: Lesson 4: Building Dynamic Queries...
CHAPTER 8 Lesson 5: Creating a Trip Detail Page In this lesson you will enhance the Compass Travel Trip Maintenance application. This lesson contains the following exercises: Exercise 1: Creating a Trip Detail page......... . . 86 Exercise 2: Avoiding the potential security risk when using dynamic SQL .
Exercise 1: Creating a Trip Detail page By design, the Trip Search Results page displays a subset of the information about a trip. To get additional information about any of the trips, the user should be able to click any row to display the detailed trip data.
Page 87
To build the CFC query: Create a blank ColdFusion page. Save the file as tripdetail.cfm in the my_app directory. Perform the following steps, or do the steps in the “Let Dreamweaver do it” section. Enter the following code: <cfinvoke component="cfdocs.getting_started.my_app.components.displaytripdetail" method="getTripDetails"...
Page 88
In the Component Location text box, enter /components/. In the Recordset name text box, enter tripDetails. In the Function text box, enter getTripDetails. In the Data source list, select CompassTravel. In the Table list, select trips. Click OK. When asked whether to include dependent files, click Yes. Click OK.
Page 90
Add the following code at the end of the file: </body> </html> Save the file. To view the Trip Detail page: Open a browser. Enter one of the following URLs, which use the tripID of 24, which specifies the Rio Cahabon Rafting trip: http://localhost/cfdocs/getting_started/my_app/tripdetail.cfm?ID=24 Note: If you are using the built-in ColdFusion server, enter...
Reviewing the code The following table describes the ColdFusion code that you use to build the Trip Detail page: Code Explanation <cfcomponent> tag creates a CFC. The cfcomponent cffunction <cffunction name="getTripDetails" creates a method named in the CFC; the getTripDetails access="public"...
If a user called the Trip Detail page using the following statement: http://localhost/cfdocs/getting_started/my_app/tripdetail.cfm?ID=24;DROP+trips the SQL database management system executes the proper SQL SELECT statement, and then immediately erases the Trips table from the database. Protecting your application To ensure that your application is protected from such an attack, you can exploit the fact that the ID must be a numeric value.
To test the revised page: View the tripsearchform.cfm page from the my_app directory in your browser. In the Trip Location drop-down list, select Begins With, and enter the value C. Click Search. The Trip Search Results page displays a hyperlink for each trip name, as the following figure shows: To view the Trip Detail page for a trip, click the trip name.
Page 94
Save the file. To format the currency and date fields on the Trips Search Results page, open the tripsearchresult.cfm file in your editor and make the changes for departureDate returnDate indicated in the table. price Save the file. To view the application’s new appearance: View the tripsearchform.cfm page in the my_app directory in your browser.
Summary In this lesson, you transformed the search facility that you built in “Lesson 4: Building Dynamic Queries” into a drill-down facility for trip queries. You built a Trip Detail page to show more information about a particular trip. You also formatted the Trip Search Results and Trip Detail pages using the CFML functions.
CHAPTER 9 Lesson 6: Creating a Main Application Page In this lesson you will enhance the Compass Travel Trip Maintenance application. So far, you created a very useful drill-down query facility. Compass Travel trip coordinators can produce lists required by management and easily locate and display information about any trip. There are several requirements that were identified in “Lesson 1: Preparing to Build the Sample Application”...
Exercise 1: Creating the main application page from the Trip Detail page In this exercise, you convert the Trip Detail page into the main Trip Maintenance application page. The main application page includes additional buttons for navigating to other ColdFusion pages and browsing the trip database records.
Page 99
To add navigation buttons to the Trip Detail page: Open the tripdetail.cfm file in the my_app directory. Insert the following code between the tags: </table> </cfoutput> <form action="navigationaction.cfm" method="post"> <input type="hidden" name="RecordID" value="#tripID#"> <!--- graphical navigation buttons ---> <input type="image" name="btnFirst" src="images/first.gif"> <input type="image"...
Reviewing the code The following table describes the navigation code for the Trip Detail page: Code Explanation <form action="navigationaction.cfm" method="post"> Form tag that identifies the navigationaction.cfm file to handle record navigation. Hidden field with the value of <INPUT type="hidden" name="RecordID" RecordID value="#tripID#">...
To test the updated application: Open your browser. Enter the following URL to view the updated tripdetail.cfm page http://localhost/cfdocs/getting_started/my_app/tripdetail.cfm?ID=8 Note: If you are using the built-in ColdFusion server, enter localhost:8500 instead of localhost. The page appears as follows: Click Search or Delete to test the database maintenance buttons. An error occurs because the Maintenance Action page does not exist.
Page 102
Chapter 9: Lesson 6: Creating a Main Application Page...
CHAPTER 10 Lesson 7: Validating Data to Enforce Business Rules In this lesson, you will create a page for the trip coordinator to add new trip offerings and update existing trips. In addition, you will add logic to validate that data entered so that it complies with Compass Travel business rules.
Exercise 1: Using an HTML form to collect data In this exercise, you develop the Trip Edit page, which provides a data entry form that is used to add new trips and edit existing trips. You validate the data entered against Compass Travel business rules.
Page 106
<TR> <TD valign="top">Photo File Name</TD> <TD><INPUT maxLength=50 size=50 name=photo></TD> </TR> </table> <p> <input type="submit" value="Save"> <input type="submit" value="Cancel" name="btnCancel"> </p> </form> </body> </html> Save the file as tripedit.cfm in the my_app directory. Reviewing the code The following table explains the use of some of the HTML tags in the Trip Edit page. For more information on HTML, consult any HTML primer.
At this point, this form does not store any information in the database and does not enforce any business rules of Compass Travel. In the next exercise, you develop the action page to enforce the business rules. Exercise 2: Creating a simple action page In this exercise, you develop an action page that you will eventually use to insert or update trip data passed from the Trip Edit page into the trips table of the Compass Travel database.
Exercise 3: About data validation To ensure that the data entered in the trip edit form is valid, Compass Travel has identified a set of business rules for capturing and editing trip information. A fundamental concern is ensuring that the captured data is suitable for the column definitions in the Trips table. This type of validation on a single field is often referred to as a single-field edit.
Exercise 4: Providing server-side validation In this exercise, you will learn about the following tasks: • Creating a local variable to indicate whether data entered in the form conforms to the Compass Travel business rules • Ensuring that a value was entered •...
Page 110
Because you did not yet add any logic to test whether any values entered in the form are valid, the page works precisely as before, displaying a message that indicates the database was updated, without actually performing the update. For more information about using the tags, see ColdFusion MX Developer’s Guide cfset cfif...
Page 111
Evaluating check box and radio button variables Business rule 8 in the Compass Travel new trip policy requires you to test the value of the check box form variable. Check box and radio button variables are only passed depositRequired to the action page when the user selects these options on the form. An error occurs if the action page tries to use a variable that was not passed.
Page 112
Note: You have already entered validation code for business rule 1. Validation code for business rule 10 is described in more detail later in this lesson. Rule Description Validation code All trips must be accompanied <!--- Trip description is required. ---> <cfif Form.tripDescription EQ "">...
Page 113
Rule Description Validation code The trip’s price and base cost <!--- Base Cost is required and must be numeric. ---> <cfif Form.baseCost EQ "" or are required. Both values are IsNumeric(Form.baseCost) EQ False> positive numeric values. The <cfset IsOk = "No"> trip price must have at least a <cfoutput>...
To test the validation code: View the tripedit.cfm page in the browser. In the form, enter 500 in both the Price and Base Cost fields. Click the Save button. The trip price error message displays: "Price must be marked up at least 20% above cost." Click the browser Back button to return to the tripedit.cfm page.
Page 115
ColdFusion form tags include the following attributes: Attribute Description validate The data type that the field tag validates against. Values include: integer, date, time, telephone, zipcode. message The error message that appears if validation fails. range The range of permissible values for this tag. required An indicator of whether data is required for the corresponding tag.
Page 116
Modifying the Trip Edit page to use ColdFusion form tags In this exercise, you use the ColdFusion form tags to move the validation of many business rules from the server to the client. To do this, you change the HTML form tags in the tripedit.cfm page to ColdFusion form tags that validate these fields on the client side.
Page 117
Rule Description Validation code The maximum number of <cfinput name="numberPeople" size="6" people permitted on the required="Yes" trip must be specified. validate="integer" message="The number of people field must be a number and cannot be blank."> The trip departure and <cfinput name="departureDate" size="10"...
Page 118
Open the tripeditaction.cfm file in the my_app directory and delete the code for the following single-field validation rules: Trip name is required. Trip description is required. Trip leader is required. Photo filename is required. Number of people is required and must be numeric. Trip location is required.
To test the modified code: View the tripedit.cfm page in a browser. Test the client- and server-side field validations by filling out the fields on the form and clicking Save. Testing recommendations: Omit required fields such as trip name or location. Make the departure date an invalid date, such as 12/32/2002.
Replace the following eventtypes code lines: <cfselect size="1" name="eventType" required="Yes" message="Type of event must be selected."> <option value="1" selected>Surfing</option> <option value="2">Mountain Climbing</option> <option value="3">Mountain Biking</option> </cfselect> with these lines: <cfselect size="1" name="eventType" required="Yes" message="Type of event must be selected."> <cfoutput query="GetEvents"> <option value="#GetEvents.eventTypeID#">...
Page 121
function, see CFML Reference. For more information about the FileExists To verify that the photo filename exists: Open the tripeditaction.cfm file in the my_app directory. Add logic to check that the user entered a valid photo filename by copying the following code immediately following the first statement: <cfset isOk = "Yes">...
Reviewing the code The following table describes the code used to verify whether the photo file exists: Code Explanation <cfset PhotoLocation = tag sets the value of the PhotoLocation path to cfset "C:\CFusionMX7\wwwroot\cfdocs\ the appropriate directory. getting_started\photos\"> Note: The code snippet shows one value for Windows systems.
CHAPTER 11 Lesson 8: Implementing Browsing and Searching In this lesson, you will further enhance the Compass Travel Macromedia ColdFusion application by providing code to implement the navigation and searching functions. This lesson contains the following exercises: Exercise 1: Enabling users to browse trip details ........123 Exercise 2: Determining actions based on which button a user clicks .
Page 124
Using dynamic SQL to browse the Trips table uniquely identifies a trip in the Trips table. In “Lesson 6: Creating a Main tripID Application Page” on page 97, you displayed the Trip Detail page for a trip by passing the ID as a parameter of the URL.
Page 125
Limiting the number of result rows Each of the SQL statements in the preceding table returns a result set of trips rows. The result set can range from zero to any number of rows. The Navigation Action page must limit the result set count to 1, because only the initial row in the result set appears on the Trip Detail page.
Page 126
Reviewing the code The following table describes the code used to process the navigation button requests: Code Explanation tag identifies that a query <cfquery cfquery name="TripQuery" named TripQuery is executed against dataSource="CompassTravel" the CompassTravel data source. The maxRows=1> number of rows returned cannot exceed =1).
Exercise 2: Determining actions based on which button a user clicks “Lesson 6: Creating a Main Application Page” on page 97, you added buttons to the Trip Detail page to let users search and modify the trips database; however, because you had not yet written the code to implement these capabilities, ColdFusion displayed an error when you clicked the buttons.
Reviewing the code The following table describes the code that executes when the user clicks the Search button: Code Explanation <cfif IsDefined("Form.btnSearch")> If the Form.btnSearch variable exists " " <cflocation url= tripsearchform.cfm > because the user clicked the Search button, go to the page tripsearchform.cfm.
CHAPTER 12 Lesson 9: Enabling Database Maintenance In this lesson, you will enable maintenance of the trips database. The exercises will guide you through the steps of adding the database update logic to delete trips, add new trip offerings, and update existing trips in the Compass Travel database.
Page 130
The SQL DELETE statement removes existing rows in a relational table. The DELETE statement has the following format: DELETE FROM table_name WHERE column_name = some_value For example, the database table named Clients contains holds information about people, in the following rows: LastName FirstName Address...
To test the delete capability: View the tripdetail.cfm page in a browser. The current trip is Nepal. Notice that the destination for the Nepal Summit Challenge trip is Imji Himal, Nepal. Click Search. The Trip Search page appears. In the Trip Search page, select Begins With in the selection box for Trip Location. Enter Imji in the Trip Location field.
Page 132
For example, the database table named Clients contains information about people in the following rows: LastName FirstName Address City Jones 12 State St Boston Peter Green 1 Broadway New York To add a record to the table, use the following statement: INSERT INTO Clients VALUES ('Smith', 'Kaleigh', '14 Greenway', 'Windham') After the database management system processes the preceding statement, the table contains the...
Page 133
To add data using a SQL INSERT statement and a cfquery tag: Open the tripeditaction.cfm file in the my_app directory. Locate the tag near the end of the file. After the <cfif isOk EQ "Yes"> <H1>Trip Added line, add the following code in the following table to insert the data from the Form </H1>...
Page 134
To test the modified code: Open the tripedit.cfm page in your browser. In the tripedit.cfm page, enter in the fields the values in the following table, and then click Save. Field Value Trip Name NH White Mountains Event Type Mountain Climbing Trip Description Climb the 5 highest peaks in the New Hampshire White Mountains.
Reviewing the code The following table describes the SQL INSERT and code that ColdFusion uses to add cfquery data: Code Explanation Using the attribute, the tag connects to the <cfquery name="AddTrip" datasource cfquery datasource="CompassTravel"> CompassTravel data source and returns a result set identified by attribute.
Page 136
To add data using cfinsert: Open the tripeditaction.cfm file from the my_app directory in your editor. Remove the entire AddTrip code block that you added in Exercise 2: Adding trips with cfquery SQL INSERT statements: <cfquery name="AddTrip" datasource="compasstravel"> INSERT INTO Trips (tripName, eventType, tripDescription, tripLocation,departureDate, returnDate, price, tripLeader, photo, baseCost, numberPeople, depositRequired) VALUES ('#Form.tripName#', #Form.eventType#,...
To verify that the trip was saved, open the tripsearchform.cfm page in the my_app directory in your browser. In the Trip Search page, in the Trip Location drop-down list, select the Begins With option, and enter the value Nor in the text box. Click Search.
Reviewing the code The following tables describes the code: cfinsert cfupdate Code Explanation <cfif not isdefined("form.tripID")> function determines whether IsDefined <cfinsert datasource="CompassTravel" the hidden field was passed to the tripID tablename="Trips"> action page from the tripedit.cfm page. If there <cflocation url="tripdetail.cfm"> is a current trip, the function returns IsDefined...
Insert the highlighted code: <cfelseif IsDefined("Form.btnEdit")> <!--- Code to execute if the user clicked Edit. ---> <cflocation url="tripedit.cfm?ID=#Form.RecordID#"> <cfelseif IsDefined("Form.btnAdd")> <!--- Code to execute if the user clicked Add. ---> <cflocation url="tripedit.cfm"> Save the file. Exercise 6: Inserting values in the edit form Notice that when the user clicks the Add button, the maintenanceaction.cfm page navigates to the tripedit.cfm page without passing any arguments.
Page 141
Code Explanation <TD><cfinput name="departureDate" Set the value of the Departure Date to size="10" be blank if the ID is undefined; required="Yes" otherwise, set the value equal to the validate="date" Departure Date that appeared on the value="#departureDate#" Trip Detail page. message="Departure date must be a valid date."> </TD>...
Page 142
Reviewing the code The following table describes the code that ColdFusion uses to properly initialize the Trip Edit form: Code Explanation The ColdFusion function <cfif IsDefined("URL.ID")> IsDefined <cfquery name="TripQuery" datasource="CompassTravel" determines whether an ID argument maxrows="1"> was passed as part of the invoking SELECT tripName, eventType, tripDescription, URL.
.147. Exercise 1: About the Login Wizard ColdFusion MX 7 provides Macromedia Dreamweaver MX Extensions to assist you in creating a ColdFusion MX application that requires login, or user, authentication. The user authentication interface that you create using the Login Wizard can perform simple authentication, authentication against a Microsoft Windows NT domain, or authentication against a Lightweight Directory Access Protocol (LDAP) server.
Page 144
Preparing to run the Login Wizard Before using the Login Wizard, you should determine the following information: • Which of the authentication types you want to use to restrict access to your application. The types include the following: LDAP, which grants access to users who have an entry in a known LDAP server. NT, which grants access to users who belong to the specified Windows domain.
Page 145
Adding user authentication to an existing application You can use the Login Wizard to add user authentication to an existing application. The Login Wizard modifies the existing Application.cfc. If your application uses an Application.cfm file instead of an Application.cfc file, ColdFusion MX ignores the Application.cfm file when the Login Wizard creates the Application.cfc file in the same directory as the existing Application.cfm file.
Page 146
Creating a login using simple authentication When you create a Login using simple authentication, you specify one username and password that all users enter to gain access to your application. To create a login using simple authentication: Start the Login Wizard. (See “Starting the Login Wizard”...
Creating a login using Windows NT authentication Start the Login Wizard. (See “Starting the Login Wizard” on page 145.) Select NT as the type of authentication. Select one of the following: Basic Authentication to use the browser dialog box to prompt the user for credentials ColdFusion Login page to prompt the user in a web page Enter the name of the domain for whose members you want to grant access to your application.
To test the authentication: Open the tripdetail.cfm page in the my_app directory in your browser. When prompted, enter CompassStaff as the user name. Enter Columbus92 as the password. Summary In this lesson, you learned how to use the Login Wizard to provide user authentication for a site, and added user authentication to the Compass Travel application.
Page 151
Macintosh OS X retrieving data 61 data source 53 reusable code, writing 63 saving CFM pages 17 rows Macromedia ColdFusion MX 7. See ColdFusion MX 7 adding 131 Macromedia Dreamweaver MX limiting number of 125 configuring 51 updating 137 defined 50...
Page 152
database design 43 AND operator 75 enforcing business rules 122 commands 34 file structure, described 49 data source 36 implementing browsing and maintenance functions described 34, 37 dynamic 75, 124 preparing to use 41 INSERT statement 131 requirements 48 ORDER BY statement 36 validating trip photo 120 security risks 91 working directories 47...
Need help?
Do you have a question about the COLFUSION MX 7-GETTING STARTED BUILDING COLDFUSION MX and is the answer not in the manual?
Questions and answers