Summary of Contents for MACROMEDIA COLDFUSION MX 61-GETTING STARTED BUILDING COLDFUSION MX
Page 1
Getting Started Building ColdFusion MX Applications...
Page 2
If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites.
If you did not install the ColdFusion MX example applications, you can download the tutorial files from the ColdFusion Support center on the Macromedia website. About Macromedia ColdFusion MX documentation The ColdFusion MX documentation is designed to provide support for the complete spectrum of participants.
Viewing online documentation All ColdFusion MX documentation is available online in HTML and Adobe Acrobat Portable Document Format (PDF) files. Go to the documentation home page for ColdFusion MX on the Macromedia website: www.macromedia.com. Introduction...
Page 9
PART I Welcome to ColdFusion Part I provides an introduction to ColdFusion. It defines ColdFusion and provides an overview of the ColdFusion Markup Language (CFML). It also provides generic database concepts, and information about how to prepare your development environment for using the tutorial in Part II of this book. Introducing ColdFusion MX .
What is ColdFusion MX? ColdFusion MX is a powerful web application server that lets you create robust sites and applications without a long learning curve. ColdFusion MX does not require coding in traditional programming languages (for example, C/C++, Java, XML), although it supports these traditional programming languages.
Development tools While you can code your ColdFusion application with NotePad or any HTML editor, 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 4, “Configuring Your Development...
Using ColdFusion MX with Macromedia Flash MX Macromedia Flash MX is designed to overcome the many limitations of HTML and solve the problem of providing efficient, interactive, user interfaces for Internet applications. ColdFusion MX is designed to provide a fast, efficient environment for developing and providing data-driven Internet applications.
CHAPTER 2 CFML Basics This chapter introduces the basic elements of CFML, including how to create ColdFusion pages, and use variables, functions, conditional processing, and form processing. Contents Working with ColdFusion pages ..........16 Understanding CFML elements.
• VI or EMACS (UNIX® systems) 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
To create a ColdFusion page: Open your editor and create a blank file. Enter the following code on the page: <html> <head> <title>A ColdFusion Page</title> </head> <body> <strong>Hello world, this is a ColdFusion page.</strong> <br> <cfoutput> Today’s date is #DateFormat(Now())# </cfoutput> </body>...
The following figure shows the cfpage.cfm 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 page then selecting View Source. Compare the browser source code with the source code that appears in your editor. Notice that the CFML tags were processed on the page but did not appear in the source that was returned to your browser.
Most often the end tag encloses the tag name in brackets and includes a 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
function returns a value as a string and formats that value with two decimal DollarFormat places, thousand separator, and dollar sign. The pounds signs (#) around the function instruct ColdFusion to evaluate the content between the pound signs and display the value. Functions and parentheses All functions have parentheses, regardless of whether the function acts on data.
If you did not include the pound signs around the function, DateFormat(Now(), "mm/ddyyy") ColdFusion would not evaluate the function and the previous example would display your source code, as follows: For more information about how to use pound signs with functions, see Developing ColdFusion MX Applications.
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...
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.
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 book.) As mentioned, it is important that elements are identified properly in your expression so ColdFusion processes them as expected, and you can avoid unnecessary errors.
Page 25
Specifying quotation marks around values When assigning literal values to variables, you must surround the literal value with double quotation marks or single quotation marks. ColdFusion interprets the content between the quotation marks as a literal value and assigns that value to the variable; for example: <cfset my_first_name = "Kaleigh">...
Nonsupported Equivalent ColdFusion logical operator decision operator Description >= GTE, Tests for greater than or equal to GREATER THAN OR EQUAL TO < > IS NOT, NEQ, Tests for nonequality. NOT EQUAL CONTAINS Tests whether a value is contained within a second value.
Page 27
You use conditional processing to customize the behavior of your application. Conditional processing facilitates decision making and lets you control how the code on a page is processed. In ColdFusion, you implement conditional processing with flow control tags. These tags are similar to other programming language control elements, such as , and then...
The output of this statement is based on the value entered by the user. If the user enters MA cfif in the state form field, the state tax results returned is 8.5%. If the user enters VA in the state form field, the state tax results returned is 8.2%.
In order for the form page to find its corresponding action page, the action statement in the form tag must be correct. The form tag includes the information that tells the server where to send the data that it collects. It also tells the server how to send it. To processes these instructions to the server, the form tag uses the following syntax: <form action="actionpagename.cfm"...
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 Understanding database basics .
Understanding database basics Even though you do not need a thorough understanding of database management systems to create ColdFusion applications, you must understand some basic concepts and techniques about databases. The information in this chapter will get you started with ColdFusion. 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.
Understanding relational tables In a database, you can organize data in multiple tables. For example, if you manage a database for the Human Resource department, you might have one table that lists all the employees information and another table that lists all the departments: Because you have multiple departments for employees, but you would not store the information about the departments in every employee row for several 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.
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 need to include SQL statements in your CFML statements;...
Verifying the tutorial file structure Before you begin the tutorial, verify that the configuration of the computer where ColdFusion is installed matches the file structure described in the following sections. The files required to complete the Compass Travel tutorial (in Part II of this book) are installed under the web server root directory.
To access the ColdFusion Administrator, do either of the following: • Select Start > Programs > Macromedia ColdFusion MX > ColdFusion MX Administrator. • Open a browser and go to one of the following URLs:...
Page 40
Specify the following: Field Action Database File text box Specify the location of the CompassTravel.mdb file. Click Browse to locate and select the CompassTravel.mdb file. By default, ColdFusion MX installs the CompassTravel.mdb file in one of the following locations: • For third-party web server configurations: web_root\cfdocs\getting_started\db •...
Page 41
Specify the following: Field Action JDBC URL Enter the following JDBC URL for the Compass Travel PointBase files: jdbc:pointbase:compasstravel,database.home=/<home location>/ wwwroot/cfdocs/getting_started/db The following is the default home location for stand-alone ColdFusion web server configurations: /opt/coldfusionmx/wwwroot/cfdocs/getting_started/db Driver Class Enter the following driver class: com.pointbase.jdbc.jdbcUniversalDriver Driver Name Specify PointBase.
Enabling debugging options The ColdFusion MX Administrator provides a variety of debugging settings that let you enable debugging information on a server-wide basis. If you are working on a development system, you can have these options turned on all the time. However, if you are working on a production system, you most likely will not want to have these options turned on, because the debugging information can appear on the bottom of an application page or in a dockable tree in your browser.
Page 43
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.
MX window Dreamweaver MX supports the latest ColdFusion MX features and tags. It also includes Macromedia HomeSite+, which combines all the features of ColdFusion Studio and HomeSite 5, along with support for the latest ColdFusion MX tags. With Dreamweaver MX or HomeSite+, you can author and test your application code from a local or remote client.
Dreamweaver MX online Help includes ColdFusion MX documentation. If you plan to use Dreamweaver MX or HomeSite+ to build the sample ColdFusion application in Part II of this book, see the following sections for information about configuring these tools for ColdFusion development. Macromedia development environment tools...
ColdFusion Markup Language (CFML). Configuring HomeSite+ for ColdFusion development Before you use Macromedia HomeSite+ to create the sample application in Part II of this book, you must configure HomeSite+ to recognize the tutorial files and data sources. To use HomeSite+ to create the sample application: Establish a secure connection to the ColdFusion server environment where the tutorial files are installed.
Page 47
PART II Building a ColdFusion Application Part II provides a tutorial that steps you through building a sample ColdFusion application. It consists of six lessons: Lesson 1: Preparing to Build the Sample Application ....49 Lesson 2: Writing Your First ColdFusion Application .
CHAPTER 5 Lesson 1: Preparing to Build the Sample Application In this tutorial, you will build a simple ColdFusion web application for a fictitious travel company called Compass Travel. Compass Travel markets a wide range of adventure trips to the public through its website.
Determining the application functional requirements Before you can build the sample application, you must understand the functional requirements underpinning its design. The design of the sample application centers around the daily tasks performed by Compass Travel’s trip coordinators. These tasks are listed in the following table: Trip coordinator task Description Produce current trip...
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: •...
Designing the database for your application After you identify the information to collect, you must consider where to store the data. Prior to creating the data collection form and instructing ColdFusion where to store the form data, you must have a database ready to accept the data. 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.
Page 53
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.
Developing the sample application Given the application functional requirements and the database provided, you are ready to use ColdFusion to develop the Trips Maintenance application. The remaining lessons in the tutorial will 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.
How to proceed Each lesson in the tutorial is designed to let you proceed at your own pace. At any time, you can stop and later return to that place in a lesson so that you can complete all the sections in the lesson.
Page 56
• Text editor or IDE (Interactive Development Environment) Macromedia recommends that you use Dreamweaver MX. However, you can use HomeSite+, ColdFusion Studio, any text editor, or IDE. In the exercises in this tutorial, the term editor means Dreamweaver MX, HomeSite+, ColdFusion Studio, or any text editor or IDE of your choice.
CHAPTER 6 Lesson 2: Writing Your First ColdFusion Application In this lesson, you begin the construction of a ColdFusion web application for the fictitious company, Compass Travel. The exercises in this lesson guide you through the steps of creating queries and forms to search for and display trip offering information from the Compass Travel relational database.
Creating your first ColdFusion application As you recall from Lesson 1: Preparing to Build the Sample Application, two of the requirements for the Trip Maintenance application are the ability to generate trip listings and a trip query facility. You will create a search interface that meets both of these requirements in this lesson. The following list identifies the components that you will create in this lesson: •...
• Trip Search Results page The purpose of the Trip Search Results page is to display the results of a trip search. The primary users of these components are the Compass Travel coordinators and agents, not the general public. Application development steps You will review or participate in the following application construction steps: Steps Description...
Using a web page to list trips To help Compass Travel agents take trip reservations by telephone and in person, the trip coordinator maintains a list of current trip offerings. Years ago, the coordinator would type the list and fax it to the various Compass Travel offices in an effort to keep everyone informed. When Compass Travel built an intranet accessible by all offices, the trip coordinator added the following HTML web page to the site: Each time the Trip List HTML page is rendered in a browser, it displays the same web page.
Page 61
Consider a table named Clients to hold information about people with the following rows: LastName FirstName Address City Jones 12 State St Boston Adams Anita 521 Beacon St Boston Green Peter 1 Broadway New York To select the columns named LastName and FirstName, use the following SELECT statement: SELECT LastName, FirstName FROM Clients The result of this SQL statement contains the following data: LastName...
The result of the preceding SQL statement contains the following data: LastName FirstName Jones Adams Anita You can compose a WHERE clause with one or more conditions; these are called subclauses. You join subclauses using the operators AND and OR.The AND operator displays a row if ALL conditions listed are True.
Displaying the query result using cfoutput Chapter 2, “CFML Basics,” on page 15, you learned that the ColdFusion tag is an cfoutput easy mechanism to display literal text and the contents of variables. Additionally, the cfoutput tag significantly simplifies displaying the results of queries. When used to display the results from a query, the tag automatically loops through the record set for you.
Page 64
Exercise: building a query using SQL, cfquery, and cfoutput Follow these steps to build a query that lists the current trips from the Compass Travel database. To build the query: Open an editor and create a new ColdFusion page (.cfm). At the top of the file, enter the following code to dynamically retrieve the names of the current trips listed in the Compass Travel database: <cfquery name="TripResult"...
Page 65
To enhance the query results: To sort the trip names in alphabetical order in the triplisting.cfm page, modify the SQL SELECT statement within the tags as follows: cfquery SELECT tripName FROM trips ORDER BY tripName To display the departure, return date, and price for each trip, modify the same SQL statement. Modify the SQL SELECT statement, as follows: SELECT tripName, departureDate, returnDate, price FROM trips...
Developing a search capability The dynamic listings developed in the previous exercise meet many of Compass Travel’s requirements for locating trips. However, what if the number of trips were in the thousands or tens of thousands? Locating the right trip for a customer might be difficult and certainly time consuming.
Page 67
Understanding search query operators Now that you decided on the queryable columns (tripLocation, departureDate, and price), you can build a simple form that allows the user to enter values for each of these fields. If the user enters a value (for example, Boston) for the tripLocation field and leaves the other two fields blank, the search results page constructs the following SQL statement: SELECT tripName, tripLocation, departureDate, returnDate, price, tripID...
Page 68
Using SQL operators to create a search criteria page A simple design for a search criteria page presents an operator list and data entry field for each of the queryable columns. Following this pattern, a page to collect the Compass Travel Trip search criteria looks like this: Since all the code used to produce the search criteria page is HTML, you are not requested to build this page.
Page 70
When the user enters the search criteria on the Trip Search form and clicks the Search button, the form fields are then posted to the Trip Search Results page. The posted field values compose the WHERE clause in the SQL SELECT statement. The following example lists the WHERE clauses that can be generated depending on the criteria set on the search page: WHERE tripLocation = 'China' WHERE tripLocation Like 'C%'...
Page 71
For each search criterion on the Trip Search form, the code within the Trip Search Results page must do the following: • Verify that the user entered data in the search criterion’s value field using the tag; for cfif example <cfif Form.tripLocationValue GT "">...
Completing the Trip Search Results page In the following exercises you will test and modify tripsearchresults.cfm. In the first exercise, you will test the Trip Search Results page by entering criteria on the Trip Search form and inspecting the results. In the second exercise, you will finish the code to construct the complete WHERE clause for all three queryable columns from the Trip Search form.
Page 74
Exercise: enabling the departure and price criteria on the Trip Search form In this exercise you will modify the Trip Search Results page to add the criteria needed for the departure and price query. To enable the departure and price criteria: In an editor, open the tripsearchresult.cfm page in the my_app directory, then locate the following comment line: <!--- Query returning search results --->...
Verify that the are now considered in the query, as in step 4 in the price departureDate previous exercise: Open the tripsearch.cfm page in the my_app directory in your browser. In the Departure Date drop-down list box, select Before, enter 1/1/1900 as the date (specify 1900-1-1 on UNIX), and select Smaller Than 0 for the price.
Page 76
Chapter 6: Lesson 2: Writing Your First ColdFusion Application...
CHAPTER 7 Lesson 3: Creating a Main Application Page In this lesson you will enhance the Compass Travel Trip Maintenance application. The exercises in this lesson guide you through the following steps: • Transforming the search facility that you built in the previous lesson into a drill-down facility for trip queries •...
Enhancing the Trip Maintenance application In this lesson you will enhance the Trip Maintenance application that you created in Lesson 2: Writing Your First ColdFusion Application. You will modify the application to include a main application page that lets Compass Travel employees do these tasks: •...
Page 79
• Enhanced Trip Search Results page The original purpose of the Trip Search Results page Lesson 2: Writing Your First ColdFusion Application was to display the results of a trip search. In this lesson, you will enhance this page to provide a useful drill-down mechanism for accessing additional information about trips that meet the search criteria.
The primary users of these components will be the Compass Travel coordinators and agents, not the general public. Showing additional trip details 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 displayed, the user should be able to click on any row to display the detailed trip data.
Page 81
Exercise: building a Trip Detail page Follow these steps to build a Trip Detail page. To build a Trip Detail page: Open your editor and create a new ColdFusion page. Remove any lines that your editor adds. To create a query to select a single trip from the Trips table, enter the following code: <cfquery name="TripQuery"...
Page 83
The following page shows the expected result: Reviewing the code The following table describes the ColdFusion code used to build the Trip Detail page: Code Explanation <cfquery name="TripQuery" tag includes a attribute. This attribute cfquery maxRows dataSource="CompassTravel" limits the number of result rows brought back from the maxRows=1>...
As you can see, you can build comprehensive database query applications using CFML and dynamic SQL. To further test the new Trip Detail page that you created, you will link it to the search facility that you built in Lesson 2: Writing Your First ColdFusion Application.
Linking the Search Results page to the Trip Detail page In the next exercise you will modify the Trip Search Results page to let the user view the details of any trip. To do this, you will convert the trip name entries in the results page to links, which will display the trip’s detailed information in the detail page.
Enhancing the look of the search results and detail pages The Trip Maintenance search now provides a useful drill-down mechanism for locating trips. While this application is functionally sound, the appearance of the dates and dollar amounts could be improved. ColdFusion provides several functions to improve the application appearance.
Page 87
When a query variable is referenced within a block, the qualifying cfoutput query_name assumed to be the query identified in the QUERY attribute of the tag and does not cfoutput need the . That is why the variable is unqualified in the qualifier query_name CurrentRow previous modulus code example.
Page 88
The Trip Search Results page appears: In the Trip Search Result page, click the link for Riding the Rockies. The properly formatted Trip Detail page appears: Chapter 7: Lesson 3: Creating a Main Application Page...
Creating the main application page from the Trip Detail page To this point in the tutorial, 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, however, that you have not addressed: the ability to...
Page 90
<!--- graphical navigation buttons ---> <input type="image" name="btnFirst" src="images/first.gif"> <input type="image" name="btnPrev" src="images/prev.gif"> <input type="image" name="btnNext" src="images/next.gif"> <input type="image" name="btnLast" src="images/last.gif"> </form> Note: Notice that the current trip record ID (tripID) is hidden within the form code. This is desirable because the action page must have the current record ID in order to build the query that navigates to the appropriate record in the trips database table.
Reviewing the code The following table describes the navigation code in the Trip Detail page: Code Explanation Form tag identifying <form action="navigationaction.cfm" method="post"> navigationaction.cfm to handle record navigation. Hidden field with the value of <INPUT type="hidden" name="RecordID" RecordID value="#tripID#"> the current tripID <input type="image"...
Save the file and view the updated tripdetail.cfm page in a browser (http://localhost/cfdocs/ getting_started/my_app/tripdetail.cfm?ID=8). 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. The Maintenance Action page is required to process the maintenance button requests.
CHAPTER 8 Lesson 4: Validating Data to Enforce Business Rules In this lesson, you will enhance the Compass Travel Trip Maintenance application. The exercises in this lesson will guide you through the steps of enhancing the application to provide a page for the trip coordinator to add new trip offerings and update existing trips.
Enhancing the Trip Maintenance application In this lesson and the next, you will create the code to implement the remaining maintenance buttons on the main Trip Maintenance application page. The remaining buttons are Add and Edit. You will develop the data entry form to capture new trip information and validate the data entered against Compass Travel business rules.
Exercise: view the source and test the Trip Edit page To view the source and test the Trip Edit data collection form: Open an editor, then locate and open the file tripedit1.cfm in the solutions directory \cfdocs\getting_started\solutions under your web root directory. Review the HTML source code used to create the Trip Edit page.
The following table lists the Compass Travel business rules for capturing and editing trip information. This table identifies which rules require single-field or cross-field editing. Compass Travel new trip policy Edit type All trips must be named. Single-field All trips must be accompanied by a full description. Single-field Each trip must be categorized by event type.
Page 97
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. Therefore, an error occurs if the action page tries to use a variable that was not been passed.
Page 98
To build trip edit action page and validate data passed: Open an editor and create a new page called tripeditaction.cfm in the my_app directory. The new page appears as follows: <html> <head> <title>Untitled</title> </head> <body> </body> </html> To ensure that Compass Travel business rule 7 is met, insert the following code above the tag on the tripeditaction.cfm page.
Test various combinations to make sure all the Compass Travel business rules are enforced by filling out the fields on the form and clicking save. Testing recommendations: Leave out required fields, such as trip name or location. Enter a non-numeric value in Number of People, such as one. Leave the entire form blank and click Save.
Page 100
Server-side validation approach (no ColdFusion form tag) The following code is on the server (tripeditaction.cfm page): <!--- Number of people is Required and must be Numeric ---> <cfif Form.numberPeople EQ "" or IsNumeric(Form.numberPeople) EQ False> <CFSET IsOk = "No"> <cfoutput>The number of people must be a number and cannot be blank. </cfoutput>...
Page 101
For each ColdFusion form tag ( , and ), assign the appropriate values: cfinput cfselect Attribute value Description required Use this attribute for fields that must be filled out or selected. validate Use this attribute for fields that requires a specific data type for validation. Values include: integer, date, time, telephone, and zip code.
<cfoutput>Return date cannot precede departure date. Please re-enter.</ cfoutput> </cfif><html> <head> <title>Trip Maintenance Confirmation</title> </head> <body> <cfif isOk EQ "Yes"> <h1>Trip Added</h1> <cfoutput>You have added #Form.TripName# to the trips database. </cfoutput> </cfif> </body> </html> View the tripedit.cfm page in a browser and test the client- and server-side field validations by filling out the fields on the form and clicking Save.
Page 103
The cfselect tag tag is an improved version of the HTML tag. Like other ColdFusion form cfselect select tags, the tag provides the attributes that validate the data cfselect required message entered. Using the tag and the preceding , you can implement the cfselect cfquery eventType...
View the tripedit.cfm page in a browser. Select the event types drop-down list. Notice that all seven event types appear in the list. Using other client-side script to reduce edits on the server If you were interested in moving as much of the business rule logic to the client as possible, you might use other client-side scripting languages, such as JavaScript.
Page 105
Another reason that rule 6 requires JavaScript scripting is that it tests the values of more than one field in a single edit. You must ensure that the return date field is greater than departure date field. To do this, you add a JavaScript function to validate the trip date range entered, and specify the function on the attribute of the tag:...
Exercise: add JavaScript-based validation code In this exercise you will modify the Trip Insert page to validate the departure and return dates using the JavaScript functions provided. To validate the departure and return dates using JavaScript functions: Open tripedit.cfm in your editor and do one of the following: Copy example code provided Copy the tripedit3.cfm file from the solutions directory and rename it to tripedit.cfm in the my_app subdirectory...
Page 107
You used the attribute for the photo tag to ensure that a filename is entered. required cfinput Now you must make sure that the file exists in the right directory so the application can display it to customers. Since browser clients are prohibited from doing standard file I/O (input/output) on the web server, the Trips Maintenance application will use server-side validation to ensure the existence of the photo file.
To verify that the photo filename exists: Open the tripeditaction.cfm in the my_app directory in your editor. In the tripeditaction.cfm page, do the following: Add logic to check that the user entered a valid photo filename by copying the code from the photofilecheck.txt file in the solutions directory pasting it immediately following the first <cfset isOk = "Yes">...
CHAPTER 9 Lesson 5: Implementing the Browsing and Maintenance Database Functions In this lesson, you will enhance the Compass Travel ColdFusion application by providing code to implement the navigation and maintenance database functions. This lesson explains how to do the following tasks: •...
Enhancing the Trip Maintenance application In this lesson, you will make enhancements to the sample Trip Maintenance application that you created in previous lessons. In Lesson 4: Validating Data to Enforce Business Rules, you added buttons to the Trip Detail page to browse, add, edit, delete or search for records in the database. In this lesson you will build the action pages that implement the actions for these buttons.
Maintenance action page The maintenance action page processes a user’s maintenance request from the Trip Detail page. The request can be any of the following actions: • Delete the currently displayed trip. • Launch the search facility. • Add a new trip (implemented in the previous two lessons). •...
Page 112
SQL statement to navigate to Navigation button correct trip ID SQL statement description Next Row SELECT tripID FROM trips Returns the list of all greater than 6 tripIDs in ascending (7,8,9...) order. WHERE tripID > 6 ORDER BY tripID Last Row SELECT tripID FROM trips Returns the list of all in descending...
Page 113
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" will be executed dataSource="compasstravel" against the "CompassTravel" data maxRows=1> source. The number of rows returned cannot exceed 1 ( =1).
Click Previous Row. The Trip Detail page shows information about the first trip. Click Last Row. The Trip Detail page shows information about the last trip. Click First Row. The Trip Detail page shows information about the first trip. Building the maintenance action page The maintenance action page (maintenanceaction.cfm) handles the user’s maintenance requests.
Page 115
Deleting the current trip record shown on the Trip Detail page Before you can write the code to delete a trip, you must understand the underlying SQL statement to delete rows from the trips table. SQL DELETE Statement The SQL DELETE statement removes existing rows in a relational table. The format of the DELETE statement is as follows: DELETE FROM table_name WHERE column_name = some_value Consider a database table named Clients, with the following rows, that holds information about...
To handle the Search and Delete buttons from the Trip Detail page, enter the following code: <!--- SEARCH BUTTON---> <cfif IsDefined("Form.btnSearch")> <cflocation url="tripsearch.cfm"> <!--- DELETE BUTTON ---> <cfelseif IsDefined("Form.btnDelete")> <cfquery name="DeleteRecord" dataSource="CompassTravel"> DELETE FROM trips WHERE tripID = #Form.RecordID# </cfquery> <cflocation url="tripdetail.cfm">...
CHAPTER 10 Lesson 6: Adding and Updating SQL Data In this lesson, you will complete the Compass Travel Trip Maintenance application. The exercises will guide you through the steps of adding the database update logic to add new trip offerings and update existing trips in the Compass Travel database. This lesson explains how to do the following tasks: •...
Completing the Trip Maintenance application Lesson 5: Implementing the Browsing and Maintenance Database Functions, you created the tripeditaction.cfm page to contain server side edits for the trip edit data entry form. In this final lesson, you will complete the tripeditaction.cfm page. To complete the action page, you will write code to do these tasks: •...
Page 119
The table contains the following rows: LastName FirstName Address City Jones 12 State St Boston Peter Green 1 Broadway New York Smith Kaleigh 14 Greenway Windham Notice that the values inserted in the table were surrounded by single quotation marks. In SQL, you must surround any text or date values with single quotation marks but numeric values are not.
Page 120
Tip: To save time, you can copy this code from the tripsinsertquery.txt file (for Windows users) or from tripinsertqueryunix.txt (for UNIX users) in the solutions directory. Code Windows users, <!--- Insert the new trip record into the Compass Travel Database ---> using MS Access <cfquery name="AddTrip"...
Page 121
In the tripedit.cfm page, fill in the fields with the values in the following figure, then click Save: After the new trip is written to the database, the following message appears: Trip is added. To verify that the save worked, open tripsearch.cfm in the my_app directory in your browser. In the Trip Search page, enter Begins With Nor in the Trip Location criterion value in the Search page as in the following figure: Completing the Trip Maintenance application...
Page 122
Click Search. The TripResults page appears: Click the link to the NH White Mountains to display the details of the trip you just added. Verify that all the fields were saved correctly. The following page appears: Click the Delete button to delete this record so that you can reuse steps 4–8 of this exercise in the next exercise.
Page 123
Reviewing the code The following table describes the SQL INSERT and code used to add data: cfquery Code Explanation Using the attribute, connects to the data <cfquery name="AddTrip" datasource cfquery datasource="CompassTravel"> source CompassTravel and returns a result set identified by the attribute.
To add data using cfinsert: Open tripeditaction.cfm from the my_app directory in your editor and do the following: Remove the entire AddTrip cfquery that you added in the last exercise (from the beginning tag to the <cfquery name ="AddTrip" datasource="CompassTravel"> </cfquery>...
Exercise: update trip data using cfupdate In this exercise, you will add the code to update the trip data into the database. You will add the tag to the tripeditaction.cfm page. cfupdate To update the database using cfupdate: In an editor, open tripeditaction3.cfm from the solutions directory. Review the code to update the database (the last 12 lines of code).
Page 126
Notice that when the user clicks the Add button, the maintenanceaction.cfm navigates to tripedit.cfm passing no arguments. Conversely, when the user clicks the Edit button, the Trip Edit page passes the current record id. The Trip Edit page must handle both cases. When a is passed on the URL, tripedit.cfm must query the database and fill the form with the RecordID data for the corresponding trip.
Page 127
Reviewing the code The following table describes the code used 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.
Test update logic by opening the tripdetail.cfm page in your browser and doing the following tasks: Click the Edit button. Double the price of the current trip. Click Save. The ColdFusion works well for updating a single record. To update several records in a cfupdate single query, you must use the SQL UPDATE statement in conjunction with cfquery...
The table contains the following rows: PersonID LastName FirstName Green Peter Green Pitt Jess Updating multiple records statement works well when you want to update the current record within a cfupdate . Alternatively, you can update several rows within a table by issuing a single query using cfquery and the SQL UPDATE statement.
Summary In this lesson you used the tags to add and update data to a SQL table. cfinsert cfupdate You also have used the SQL UPDATE statement in conjunction with the tag to effect a cfquery trip price increase for all rows in the Trips table. You have completed the Getting Started tutorial.
12 DateFormat function, defined 16, 77 components 12 debugging information, remote clients 44 configuration, described 37–46 debugging options, enabling 43 described 12–13 debugging settings, described 42–44 introduction 11–14 markup language. See CFML using with Macromedia Flash MX 14...
Page 132
IsDefined function, defined 77 INSERTstatement 118 ORDER BY 62 security risks 84 J2EE configuration 17 SELECTstatement 60 WHERE clause 61 writing statements 35 Macintosh OS X data source 39 saving CFM pages 17 Macromedia ColdFusion MX. See ColdFusion MX Index...
Page 133
tags attributes 19 cfform 93 cfif 57 cfinput 93 cfinsert 117 cflocation 109 cfoutput 57 cfquery 57 cfselect 93 cfset 57 cfupdate 117 defined 18–19 syntax 18 tutorial adding and updating SQL data 117–130 application business rules 96 application defined 54 application page flow 110 application requirements 50 creating main application page 77–92...
Need help?
Do you have a question about the COLDFUSION MX 61-GETTING STARTED BUILDING COLDFUSION MX and is the answer not in the manual?
Questions and answers