ColdFusion 9 Developer Tutorial
By John Farrar
()
About this ebook
John Farrar
John started working with computer programming around 1977. He has had the opportunity to work on projects used by Apple, Blue Cross, Brunswick Recreation, Casio, GVSU, Johnson Controls, Sprint, and many others. This history covers over 30 years of knowledge and experience in the industry. He started doing web development over 10 years ago. In the early days of the Web ColdFusion stood out to him not just as a way to make web pages into web applications but as a maturing solid platform good for the developer, site owner, and end users. He started at version 4.5 and has been enjoying each version upgrade more and more. John owns a company called SOSensible. His company does work for large companies but has a special focus on also making sure technology is approachable beyond the enterprise. They have developed a number of Open Source solutions including COOP. COOP is a mix of Custom Tags and CFCs that provides structure while keeping development simpler. It demonstrates his love for the things that make ColdFusion/CFML a delightful language to build websites. He has spoken at national and regional conferences, online meetings, and area user group meetings. He is also an Adobe User Group manager. John knows that community is a viable and productive tool to build developers and the companies they serve. He has learned much from great resources in the community including bloggers, books, conferences, and resources to great in number to mention here. He blogs at sosensible.com for the community.
Related to ColdFusion 9 Developer Tutorial
Related ebooks
ColdFusion Interview Questions, Answers, and Explanations: ColdFusion Certification Review Rating: 0 out of 5 stars0 ratingsObject-Oriented Programming in ColdFusion Rating: 5 out of 5 stars5/5Learning Node.js for .NET Developers Rating: 0 out of 5 stars0 ratingsAngularJS Web Application Development Blueprints Rating: 0 out of 5 stars0 ratingsMastering Web Application Development with Express Rating: 0 out of 5 stars0 ratingsAn Introduction to Programming in JavaScript: Stomping Zombies with Variables, Loops, Functions and More: Undead Institute, #10 Rating: 0 out of 5 stars0 ratingsModern CSS: Master the Key Concepts of CSS for Modern Web Development Rating: 0 out of 5 stars0 ratingsProfessional C# Rating: 0 out of 5 stars0 ratingsXamarin 4 By Example Rating: 0 out of 5 stars0 ratingsCloning Internet Applications with Ruby Rating: 5 out of 5 stars5/5Wb Development full course : from zero to web hero Rating: 0 out of 5 stars0 ratingsMastering JavaFX 8 Controls Rating: 0 out of 5 stars0 ratingsPython AI Programming Rating: 0 out of 5 stars0 ratingsRails: Novice to Ninja: Build Your Own Ruby on Rails Website Rating: 4 out of 5 stars4/5jQuery for Designers Beginner's Guide Rating: 5 out of 5 stars5/5Mastering OpenGL: From Basics to Advanced Rendering Techniques: OpenGL Rating: 0 out of 5 stars0 ratingsLearning ClojureScript Rating: 0 out of 5 stars0 ratingsC#-Visual Basic Bilingual Dictionary : Visual Studio 2015 Edition Rating: 3 out of 5 stars3/5Surviving the Whiteboard Interview: A Developer’s Guide to Using Soft Skills to Get Hired Rating: 5 out of 5 stars5/5JavaScript Programming: 3 In 1 Security Design, Expressions And Web Development Rating: 0 out of 5 stars0 ratingsSchematron: A language for validating XML Rating: 0 out of 5 stars0 ratingsBootstrap for Rails Rating: 0 out of 5 stars0 ratingsRuby For Beginners: Your Guide To Easily Learn Ruby Programming in 7 days Rating: 3 out of 5 stars3/5ASP.NET 3.5 Application Architecture and Design Rating: 0 out of 5 stars0 ratingsSoftware Design Patterns A Complete Guide - 2020 Edition Rating: 0 out of 5 stars0 ratingsLearn ASP.NET MVC Rating: 4 out of 5 stars4/5Kotlin Unleashed: Harnessing the Power of Modern Android Development Category Rating: 0 out of 5 stars0 ratingsPro ASP.NET Core 3: Develop Cloud-Ready Web Applications Using MVC, Blazor, and Razor Pages Rating: 0 out of 5 stars0 ratingsXML Programming: The Ultimate Guide to Fast, Easy, and Efficient Learning of XML Programming Rating: 3 out of 5 stars3/5
Information Technology For You
Creating Online Courses with ChatGPT | A Step-by-Step Guide with Prompt Templates Rating: 4 out of 5 stars4/5Health Informatics: Practical Guide Rating: 0 out of 5 stars0 ratingsData Analytics for Beginners: Introduction to Data Analytics Rating: 4 out of 5 stars4/5How to Write Effective Emails at Work Rating: 4 out of 5 stars4/5CompTIA A+ CertMike: Prepare. Practice. Pass the Test! Get Certified!: Core 1 Exam 220-1101 Rating: 0 out of 5 stars0 ratingsHacking Essentials - The Beginner's Guide To Ethical Hacking And Penetration Testing Rating: 3 out of 5 stars3/5Cybersecurity for Beginners : Learn the Fundamentals of Cybersecurity in an Easy, Step-by-Step Guide: 1 Rating: 0 out of 5 stars0 ratingsHow To Use Chatgpt: Using Chatgpt To Make Money Online Has Never Been This Simple Rating: 0 out of 5 stars0 ratingsChatGPT: The Future of Intelligent Conversation Rating: 4 out of 5 stars4/5Computer Science: A Concise Introduction Rating: 4 out of 5 stars4/5Inkscape Beginner’s Guide Rating: 5 out of 5 stars5/5An Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5Unity Game Development Essentials Rating: 5 out of 5 stars5/5Investigating Child Exploitation and Pornography: The Internet, Law and Forensic Science Rating: 5 out of 5 stars5/5Learning Website Development with Django Rating: 0 out of 5 stars0 ratingsPersonal Knowledge Graphs: Connected thinking to boost productivity, creativity and discovery Rating: 0 out of 5 stars0 ratingsSupercommunicator: Explaining the Complicated So Anyone Can Understand Rating: 3 out of 5 stars3/5Windows Registry Forensics: Advanced Digital Forensic Analysis of the Windows Registry Rating: 4 out of 5 stars4/5Linux Command Line and Shell Scripting Bible Rating: 3 out of 5 stars3/5Data Governance For Dummies Rating: 0 out of 5 stars0 ratingsThe Basics of Hacking and Penetration Testing: Ethical Hacking and Penetration Testing Made Easy Rating: 4 out of 5 stars4/5An Executive Guide to Identity Access Management - 2nd Edition Rating: 4 out of 5 stars4/5Computer Organization and Design: The Hardware / Software Interface Rating: 4 out of 5 stars4/5Panda3d 1.7 Game Developer's Cookbook Rating: 0 out of 5 stars0 ratingsSummary of Super-Intelligence From Nick Bostrom Rating: 5 out of 5 stars5/5Practical Ethical Hacking from Scratch Rating: 5 out of 5 stars5/5CompTIA Network+ CertMike: Prepare. Practice. Pass the Test! Get Certified!: Exam N10-008 Rating: 0 out of 5 stars0 ratings
Reviews for ColdFusion 9 Developer Tutorial
0 ratings0 reviews
Book preview
ColdFusion 9 Developer Tutorial - John Farrar
Table of Contents
ColdFusion 9 Developer Tutorial
Credits
About the Author
About the Reviewers
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Web Pages—Static to Dynamic
Turning HTML into a dynamic web page
HTML requests
ColdFusion requests
Comments
Variable output
Functions
Understanding and using simple variables
Variable types
Integers
Strings
Decimals
Additional functions
Find and FindNoCase
Understanding structures
CGI variables
Let's get interactive
URL variables
Exception handling
Standard error exception
Setting page defaults
HTML links
Introduction to lists and loops
Understanding arrays
Conditional processing with If/
Conditional processing with switch
Summary
2. Basic CFCs and Database Interaction
Our first CFC
Our first object
Product (object)
Using an object constructor
Connecting to a database
Returning data from the CFC
Making our data query flexible
The basic data object concept
Object method access control
Summary
3. Power CFCs and Web Forms
The practice of protecting access
Web forms introduction
Managing our product data
Getting data to our edit page
Saving our data
Improving page flow
Adding a new record
Let's look under the hood
Summary
4. ORM Database Interaction
Introduction to ORM in ColdFusion
ORM-enabled application configuration
ORM-enabled CFCs
Understanding entities
Working with entity-object relationships
Many-to-many relationships
Working with relational data
ORM functions
Summary
5. Application, Session, and Request Scope
Life span
Introducing the Application.cfc object
Application variables
The start methods
Application start method—onApplicationStart()
Session start method—onSessionStart()
Request start method—onRequestStart()
The end methods
Request end method—onRequestEnd()
Session end method—onSessionEnd()
Application end method—onApplicationEnd()
On Error method—onError()
Scope visibility
Practical application
Universal datasource
Mappings per application
Custom tag paths per application
Summary
6. Authentication and Permissions
How ColdFusion recognizes users
Custom authentication (additional power)
Authentication data model
Customizing authentication
Extra notes
Summary
7. CFScript
Script basics
Variables
Switch/case
If/then/else
For loops
For/in loops
Do/while loops
While loops
Exception handling
Throw/abort
New functions/commands in CF9
Summary
8. CF AJAX User Interface
Changing times
HTML-based websites
Server-side languages
Browser-side applications
Flash
JavaScript
ColdFusion AJAX
Layout
Border example
HBox/VBox example
Tab example
Menus and tool tips
Styling notes
Tips
Map interaction
Summary
9. CF AJAX Forms
AJAX forms
Grid paging
Grid updates and deletes
Linked grids
Binding page elements
Binding immediately upon load
The date requestor
The autosuggest box
The directory tree
Message boxes
Progress bar
Summary
10. CF AJAX Programming
Binding
On-page binding
CFC binding
JavaScript binding
URL binding
Bind with event
Extra binding notes
Multiple radio buttons or checkboxes and multiple select
Spry binding
CFAJAXProxy
CFAJAX proxy binding
CFC proxy class objects
Client debugging
Firebug
Built-in debugging
Logging features
Customization
Automatically wired AJAX links
Execute JavaScript after loading content
Other cool commands
Post for CFAJAX calls
CFAJAX browser JavaScript API overview
Summary
11. Introduction to Custom Tags
Different forms of code reuse
CFCs
CFInclude
Custom tags
Our first custom tag
Custom header/footer tags
Nested tags
CFInclude from custom tags
Templates versus skins
Managing custom tags
CFModule approach
Tag library approach
Summary
12. ColdFusion Powered Views
What is open source?
The fun factor
Installing the library
Getting started
Happily separated
Manipulate DOM from server-side code
Turning lemons to lemonade
Separation complete
Fun with lists
Select list tag
Other list tags
Better form coding
Metadata
Smart form modes
Edit mode
Add mode
View mode
Style simplified
But wait, there's more!
Custom list item rendering
Module render option
Summary
13. Control Logic Processing
The code side of applications
The model
The controller
Shared variables
Processing request events
Event model for the coprocessor
onPageStart() method
onFirstCall() method
onPostBack() method
Form modes
beforeViewCall() method
onPageEnd() method
Remote AJAX events
Data versatility
Lists
Array of structures
Modified data field names
Query handling
Personal extension of COOP
Summary
14. Guide to Unit Testing
When to test
Mission critical
Test-driven development
Regression testing
Installing our testing software
Understanding assertions
First test class
Multiple tests
HTML view
Data view
Built-in assertions
MXUnit assertion extensions
Testing private methods
Testing included files and custom tags
Variable testing
Exception testing
A son's view of testing
Summary
A. Beyond this Book
Areas of interest
Perspectives
Business perspective
Persona reviews
Milestones
Design/marketing perspective
Developer perspective
Current technologies
AJAX
Flash (Flex/AIR)
Future
HTML 5
Devices
Scale versus implementation
Standards
Libraries
Size
Features
Begin with the end in mind
Research
Frameworks
Methodologies
B. Tools and Resources
AJAX
Firebug
jQuery
Analytics
Google webmaster tools
Coding
Conferencing and collaboration
Acrobat.com
Google Docs
GoToMeeting/Webinar
Slide-sharing sites
Data-management tools
Graphics creation/acquisition
Camtasia Studio
Color Schemer
Fireworks
Lightroom
SnagIt
Open source libraries
Project management
FreshBooks
Project Tracker
Source control
Usability
Morae
Virtual development box
XML
Index
ColdFusion 9 Developer Tutorial
ColdFusion 9 Developer Tutorial
Copyright © 2010 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: July 2010
Production Reference: 1200710
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-849690-24-9
www.packtpub.com
Cover Image by Vinayak Chittar (< vinayak.chittar@gmail.com>)
Credits
Author
John Farrar
Reviewers
Rick Mason
Tracy Charles Smith
Acquisition Editors
Douglas Paterson
Darshana Shinde
Development Editors
Darshana Shinde
Rakesh Shejwal
Technical Editor
Conrad Sardinha
Indexer
Monica Ajmera Mehta
Editorial Team Leader
Mithun Sehgal
Project Team Leader
Lata Basantani
Project Coordinator
Srimoyee Ghoshal
Proofreader
Lynda Sliwoski
Graphics
Nilesh Mohite
Production Coordinators
Adline Swetha Jesuthas
Kruthika Bangera
Alwin Roy
Cover Work
Adline Swetha Jesuthas
About the Author
John Farrar is a seasoned developer and business owner whose company specializes in web-based solutions. His love for design and solving problems has inspired successful customer projects to a number of open source solutions growing in popularity. He has learned ColdFusion, SQL, CSS/web design, AJAX, and other technologies to help fulfill the customer’s technical needs. Yet he is more about the business needs and goals than finding a way to use technology for the sake of technology. That is why he uses the handle and company name SOSensible
. Best practices are great guides but they change over time. John tries to implement and extend best practices to respond to project goals. His focus is to create solutions that are accessible, duplicatable, and sustainable which he calls ADS for short.
Some examples of his ADS compliant efforts are his SOS, COOP, and CFish projects. SOS is an application framework that embraces the personality of the developer. This lets them build applications to run on the same site but in the style they like to code. COOP is covered in this book and splits the code that looks more like an obstacle course into separate pages covering page design and business intelligence in cooperative but separate packages. CFish is his latest focus where he is seeking to bring universal web skinning to ColdFusion developers. All of these are focused on increasing functional accessibility, duplicatable reuse, and sustainable results. Best practices are great but John believes we can do better than that.
These principles and his open attitude have given him many opportunities. He has done work for Brunswick Recreation, Sprint, Apple, and Blue Cross in the enterprise realm. This knowledge has inspired and prepared him to also remember the roots of his childhood where his father was a small business owner. Realizing that small businesses make up over 90 percent of the market, he seeks to extend the practice beyond the enterprise boarders. He has also contributed to several other community projects and enjoyed speaking at national developer conventions over the years. You can follow him on his blog at http://www.sosensible.com/index.cfm/blog or at @sosensible on twitter.
About the Reviewers
Rick Mason has been a programmer for over twenty years and has been a ColdFusion developer since 1999. He started SeedChoices.com, a SaaS sales force automation solution for the farm seed industry nine years ago.
Mr. Mason is currently a web developer for Michigan State University. He has previously built solutions in the automotive, insurance, health care, and agricultural industries.
He also manages the Mid-Michigan ColdFusion Users Group, www.ColdFusion.org, and is an active member of the ColdFusion community. He’s a team member of the CF Conversations podcast and on Twitter as Rick_Mason.
Tracy Smith began working with computers at the age of 10. His first ColdFusion application was a baby pool application for a co-worker in 1998. His experience includes network integration, programming, finance, database design, and project management. Tracy enjoys working with creatively clients to architect their vision, then breaking it down into smaller technical pieces.
Tracy currently works as a Web Developer for Phase 2 Technology, based in Alexandria VA. Prior to joining Phase 2 Tracy lived in Santa Cruz, CA where he started Alpha Geek Tech, LLC, a technology consulting firm. His web experience began in the dot com days where he worked for Flipside.com. He is actively involved in the developer community and while working as the Technology Director for Quiddities Dev, Inc he spends his free time as the lead programmer and architect for 12seconds.tv (a video messaging platform) using Drupal.
He currently holds a B.S. in Computer Information Systems and Business Administration from Wingate University.
Preface
Adobe ColdFusion is an application server, renowned for rapid development of dynamic websites, with a straightforward language (CFML), powerful methods for packaging and reusing your code, and AJAX support that will get developers deep into powerful web applications quickly. However, developing rich and robust web applications can be a real challenge as it involves multiple processes.
With this practical guide, you will learn how to build professional ColdFusion applications. Packed with example code, and written in a friendly, easy-to-read style, this book is just what you need if you are serious about ColdFusion.
This book will give you a clear, concise, and, of course, practical guidance to take you from the basics of ColdFusion 9 to the skills that will make you a ColdFusion developer to be reckoned with.
ColdFusion expert John Farrar will teach you the basics of ColdFusion programming, basic application architecture, object reuse, and ORM concepts before showing you a range of topics including AJAX library integration, RESTful Web Services, Unit Testing, building custom tags, and his hybrid example of tags and objects COOP. All these together will make you the toast of your ColdFusion developer town.
This book digs deep into the basics, with real-world examples of the hows and whys, to get more done faster with ColdFusion 9.
This book's website (http://www.sosensible.com/index.cfm/books/) also covers the new features of ColdFusion Builder and additional version 9 updates.
What this book covers
Chapter 1, Web Pages—Static to Dynamic is a fast track introduction to what makes CF better than HTML and how to program with CFML.
Chapter 2, Basic CFCs and Database Interaction which makes our code easier to support is done by packaging logic into reusable containers. This chapter will introduce you to CFML-based object coding.
Chapter 3, Power CFCs and Web Forms is a chapter that shows the power you can achieve by packaging things into CFCs. Their features are faster coding, easier support, and simpler to read code with a minor up-front investment.
Chapter 4, ORM Database Interaction talks about the Object Relation Management (ORM) standard in CF9. This is a built in object technology that works with your database without creating SQL specific to each database platform.
Chapter 5, Application, Session, and Request Scope is a chapter that teaches us how controlled sharing will speed up your application and make them easier to build and understand.
Chapter 6, Authentication and Permissions shows us how to manage who can and who cannot do things.
Chapter 7, CFScript in CF9 is the first fully-featured script for CFML. This chapter will help us get familiarized with script and shows how to enjoy its new completeness.
Chapter 8, CF AJAX User Interface covers the tag-based language in CFML that lets us interact with AJAX in ways we can only appreciate. This chapter covers the UI element features in ColdFusion.
Chapter 9, CF AJAX Forms covers how ColdFusion lets us build richer forms with the power of built-in tags.
Chapter 10, CF AJAX Programming will teach us how to work in the browser when we want to use JavaScript to interact with the code. This chapter covers the common interface and how to use it.
Chapter 11, Introduction to Custom Tags shows us how to take advantage of tag-based packaging and how to do it when we desire.
Chapter 12, ColdFusion Powered Views will introduce us to a view tag library that makes forms and view code easier and much simpler to support.
Chapter 13, Control Logic Processing shows us how to interact with the events and view elements from a request controller. This chapter helps us understand a methodology of coding that makes for a logical flow of code where things fit in smartly.
Chapter 14, Guide to Unit Testing covers a growing and very beneficial concept of software development and sustainability—unit testing.
Appendix A, Beyond this Book is based on some additional thoughts from the author. This is a tutorial book and it made sense for me to put in a chapter that shares thoughts about moving beyond the reach of a single book introduction to web development.
Appendix B, Tools and Resources lists some of the tools we use at my company and thoughts on each of them. The number of tools and resources has grown in volume to the point where half of this book would cover this topic alone.
What you need for this book
To follow along in the book, you will need to have a version of ColdFusion installed. Some of the database examples are running in MySQL. Refer to this book's site (http://www.sosensible.com/index.cfm/books/) for requests of your configuration and we will seek to accommodate finding links and resources to assist your configuration.
Who this book is for
This book is for two groups of developers: New and experienced ColdFusion users.
If you are a new user, you will find that the contents of the first seven chapters will give you a solid start to development on the platform. At the book's site previously mentioned, we will collect a resource link page to assist you with moving ahead with different topics based on having read this book.
If you are not new to ColdFusion, you will find that the content of the first seven chapters is both a meaningful review and also an introduction to some of the related changes on the basics that were added in version 9.
The last half of this book is about features that go beyond the basics. They are perhaps the most popular features that people desire to learn when working with ColdFusion 9. Additional features will of course be posted on the book's site. If there are features specific to ColdFusion 8, you will find many of those in the first version of this book—ColdFusion 8 Developer Tutorial. We have tried to mix up some of the additional coverage to make getting the newer version of this book more valuable of course.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: The exception is placed on the page using
.
A block of code is set as follows:
My name is #url.name#.
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
public
output=false
>
false
/>
var myReturn = getRecordset(where : id = #arguments.id#
);
setAttributes(myReturn);
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: Let us click the + New Product link, and observe what we get
.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book— what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Tip
Downloading the example code for this book
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.
Chapter 1. Web Pages—Static to Dynamic
In this chapter, you will learn how to enhance basic HTML pages with the power and simplicity of ColdFusion. Here, we will use what we are learning to build a simple FAQ (Frequently Asked Questions) web application. We will cover the following skills in the process:
Moving from HTML to dynamic web pages
Simple and structured variables
URL and CGI variable structures
Setting default variables for pages
Debugging and exception handling basics
How lists and arrays work in ColdFusion
How to cycle through collections with looping commands
Conditional processing
Turning HTML into a dynamic web page
Let's jump right in and take a look at the difference between common HTML pages and the power of a server-side language. We will leave out the designer side
of web pages for now. This is again because we are going to focus on pragmatic programming concepts with ColdFusion.
Note
Visit this book's site at http://books.sosensible.com/index.cfm/books/ for help with things such as installing ColdFusion. If you go to this book's home page, there is also a link to the ZIP file for this book's code.
HTML requests
Let's work through some examples. Copy the tutorial/chapter_1 directory from the book's code bundle to the cfb/chapter_1 directory inside your server root. Enter http://localhost/cfb/complete/chapter_1/1_1.htm into the address bar of your browser. You will see a basic FAQ page as follows:
You should open the View Page Source from the browser and compare that to the code you see if you open the file in an editor. You will find that the pages are the same in every way. Here you will see how a normal server returns common HTML pages:
When we add ColdFusion to a web server, we get an extra step in how the pages are managed. This is why we are now able to create pages that are made dynamic from the server side of the equation. This is the same concept for all server-side languages.
Now let's get into a very basic introduction to ColdFusion. We will take this one step at a time. Here is the same code segment with common HTML. If you type this into an HTML page and load it into the browser, it will look the same in code as it does in the view source from the browser:
Question: What is a variable?
Answer:
Variables are named storage containers inside programming languages. Just think of variables as any type of named container holding any type of stored content. You simply name the container and store the content. Later you retrieve the content by using the same name.
12:53 PM
This is a screenshot of the previous html code running in the browser:
ColdFusion requests
Now we will look at a little more dynamic version of the page. The changes will be indicated so we can start to see what ColdFusion adds to the mix. You may be able to tell what is going on without any help depending on your programming background.
Copy the file named 1_1.htm and save the copy as 1_2.cfm in the same directory. Go back to the browser and this time look at this web page: http://localhost/cfb/chapter_1/1_2.cfm. You should note that this page looks the same and the code is basically the same if you use the browser view source.
Comments
We are going to add the following two lines above :
You will notice the two new lines have three dashes instead of two. This is because they are ColdFusion comments.
If you go back to your browser and refresh the page, you will find something interesting when you view its source. The new comment lines you added do not show on the page source since they are server-side ColdFusion comments. Remember to save the file before checking for results.
Next we need to create our first variables in ColdFusion. Add a line between the processing and content comments and create the following two variables inside string variables
.
Cut the actual question out of the bottom content section and paste it into the quotes of the string variable, myQuestion. Now, cut out the answer text in the content section and paste it inside the quotes of the string variable, myAnswer. (Don't forget, you can look at the previous code example if you have questions.)
Variable output
Now, we need to put the content, which we have moved to variables, back in the page. ColdFusion was the first to standardize server-side code tags. These look very much like HTML tags, but they add power and simplicity. What we need to do is wrap our entire content section with
We have to place the variables in the content section of the code with some special ColdFusion output markers. ColdFusion uses the pound symbols on both sides of the dynamic content for markers. So put #myQuestion# where you cut out the content for the myQuestion variable.
Also, place #myAnswer# where you cut out the content you pasted into the myAnswer variable. Save the file and run the page! (Check the sample code in the following section to make sure you typed things in correctly. Then refresh the page again.)
Functions
ColdFusion is very powerful and allows outputting the results of functions as well as variables. If you want you can replace the time with the function in the following code at the end of the ColdFusion code sample and you can refresh the page over and over and see that the time is being dynamically generated on the server:
Question: #myQuestion#
Answer:
#myAnswer#
#timeFormat(now())#
The now() function in ColdFusion returns the current date or time and the timeFormat() function converts the output to display text showing the time of its contents. Notice that when we update the screen, the time will be the current time on each refresh:
Congratulations! You have just created your first dynamic web page. If you are new to this technology, then work through the examples and complete the entire chapter. Then take a break. If you feel the need, come back after going through some chapters and repeat the exercises. You will be surprised by what you have learned.
Note
We will be removing the standard wrappers from most examples going forward in this book. Browsers don't need those markers to present the content. In your live site code, however, those should be included.
Understanding and using simple variables
In this section, we will look at a couple of variable types which will help you understand how ColdFusion works. First we are going to look at the different types of simple variables.
Variable types
There are four types of simple variables. These are string, numeric, Boolean, and date/time variables. They can basically have any name for a variable, but there are a few basic guidelines for naming variables:
A variable name must begin with a letter, which can be followed by any number of letters, numbers, and underscore characters. (We have found that you can start variable names with underscore also and there is enough code out there that it is unlikely to see this depreciated, if you use it.)
A variable name cannot contain spaces.
Variable names are not case-sensitive in ColdFusion. (myVariable is the same to ColdFusion as Myvariable.)
Integers
We will be covering two number classes in this lesson. First we will take a look at integers. These are numbers with no decimal value. ColdFusion supports integers between -2,147,483,648 and 2,147,483,647. It will work with numbers outside this range, but the precision will not be exact.
In the first example, we will modify the code we have been using to keep one of the string variables and add a numeric variable called myAge. The following two examples