| < Day Day Up > |
|
In this section, you learn more about <cfif> as you use it to create a simple user poll. The goal is to create a form that collects a user's answer to a multiple-choice question. When the form is submitted, your template records the answer in a database and displays the current poll results back to the user. Finally, and here's the trick, both the form and action page will be included in the same ColdFusion MX template.
First, you need to create a ColdFusion MX datasource to house user responses to your poll.
Start by creating a new Microsoft Access database, called polldata.mdb. Save it in a folder called "poll" in your Web root. Within the database, create a new table with just one field, response.
In Design view, set the field to the text datatype and set the field size to 100. Save the table as question1 and allow Microsoft Access to add a Primary Key column. In Design view, your table should look like the one in Figure 49-4.
Figure 49-4: Creating polldata.mdb in Microsoft Access
Set up the table as a ColdFusion MX datasource called polldata. See Chapter 48 for a step-by-step description of setting up a datasource.
Your form will contain a question, followed by three multiple-choice answers using radio buttons for selection.
Since this example isn't part of the Habitat Alert site, you'll need to create a new site in Dreamweaver. Title it Polls and assign it to the polls folder you created in the previous section.
Set up the site's testing server and supply an RDS login, as detailed in Chapter 48. Remember, if you're using ColdFusion MX's built-in Web server, the host name you specify in the testing server URL requires the 8500 port designation, as in http://localhost:8500/polls.
Create a new ColdFusion dynamic page within your site and save it as question1.cfm. Using Dreamweaver's Page Properties, title the page Question One.
Study the code in Listing 49-2 and the description that follows it; then add similar code to your template question1.cfm. Note that you can have any questions and answers, as long as they are consistent between the template's form and action sections.
Listing 49-2: polldata.cfm
![]() |
<cfparam name="action" default=""> <html> <head> <title>Question One</title> <meta http-equiv="Content-Type" content="text/html; charset=iso- 8859-1"> </head> <body> <cfif action is not 'go'> <!---if action is not 'go', show the form---> <form name="question1" method="post" action="question1.cfm"> <h2>Question One:</h2> <p>For whom will you vote in the next Senatorial election?</p> <blockquote> <input type="radio" name="response" value="Barney Fife"> Barney Fife<br> <input type="radio" name="response" value="Mickey Dolenz"> Mickey Dolenz<br> <input type="radio" name="response" value="Bobby Hill"> Bobby Hill<br> </blockquote> <input type="hidden" name="action" value="go"> <input type="submit" value="Vote!"> </form> <cfelse> <!---if action is 'go' user must be submitting the form, so process the data and show results---> <!--- insert user's answer into question1 table---> <cfinsert datasource="polldata" tablename="question1" formfields="response"> <!---get current totals for each response type, using the SQL aggregate function 'count'---> <cfquery name="get_barney" datasource="polldata"> select count(response) as total from question1 where response = 'Barney Fife' </cfquery> <cfquery name="get_mickey" datasource="polldata"> select count(response) as total from question1 where response = 'Mickey Dolenz' </cfquery> <cfquery name="get_bobby" datasource="polldata"> select count(response) as total from question1 where response = 'Bobby Hill' </cfquery> <!---display the results---> <h2>Question One Results</h2> <cfoutput> <h3>Your Vote:</h3> #form.response# <h3>Current Rankings:</h3> Barney Fife: #get_barney.total#<br> Mickey Dolenz: #get_mickey.total#<br> Bobby Hill: #get_bobby.total#<br> </cfoutput> </cfif> </body> </html>
![]() |
Listing 49-2 includes several items that will be new to you. So the following sections examine each one in more detail.
The opening tag in Listing 49-2, <cfparam>, is used to set a default value for a variable, that is, it only comes into play if a variable is undefined. In this case, it's also the key element, which enables you to include a form and its own action page in a single template. Note that the action defined in the <form> tag is question1.cfm, which causes this same page to reload when the user submits data.
By creating a default value for action, you're setting up your template to handle two conditions. When a user visits the page the first time, action won't be defined, so the <cfparam> tag kicks in and defines it as a blank value. Now take a closer look at the condition in the first <cfif>. It says that if action isn't "go," show the form. Otherwise (meaning if action is "go"), assume that the user is submitting the form and process the results.
Note | In ColdFusion MX, as with most programming languages, there is a marked difference between a variable that hasn't yet been defined and one that is defined but contains an empty string (""). For example, if your code calls upon a variable that hasn't been defined, ColdFusion will return an error, but it won't do so if the variable has been defined as an empty string. |
How does action get set to "go"? Take a look at the end of the form section. Just before the Submit button, action is defined as a hidden field and set to a value of go. When a user submits this form, this value gets passed as the page is reloaded, triggering the actions in the second half of the page.
Like any good programming or markup language, ColdFusion MX includes a method for commenting your code. In Listing 49-2, the phrases bracketed with <!--- and ---> are comments meant to aid you and/or other developers in understanding what's happening in a template.
Note | Although ColdFusion MX comment markers are similar to those used in HTML, note that they include an extra dash. The difference between the two is users can view HTML comments by choosing View Source in their browser. Users can't view ColdFusion comments. |
It's good programming practice to comment your pages liberally. Although your methods may be clear to you, they may not be to other developers who have to revise your templates later.
![]() |
The SQL statements you use in ColdFusion MX queries can go beyond just selecting the contents of database fields. You can also generate summarized information about your data by using SQL's aggregate functions.
These functions enable you to generate a variety of statistics about data stored in your tables. For example, consider a table that stores customer information along with the dollar totals each customer has spent at your client's store. To see the collective dollar amount spent by all of your client's Utah customers, you could use a SQL aggregate function called sum(). Assuming the database field containing the customers' spending totals was named "total_spent," your ColdFusion MX query might look like this:
<cfquery name="get_utah_totals" datasource="some_datasource"> select sum(total_spent) as total from customers where customer_state = 'Utah' </cfquery>
Note that in ColdFusion MX, you almost always use SQL's aggregate functions with an alias. In the preceding query, the alias total gives a name to the results generated by sum(total_spent). This situation enables you to refer to the figure later as #get_utah_totals.total# within <cfoutput> tags.
The sum() function is just one of many available in SQL. Other commonly used functions are shown in the following table. Each uses the format function(fieldname).
Aggregate Function | What It Does |
---|---|
Avg() | Finds the numeric average of items in the specified field |
Count() | Counts the values found in a field |
Min() | Finds the lowest number in numeric fields, or the lowest alphabetic value in text fields |
Max() | Finds the highest number in numeric fields, or the highest alphabetic value in text fields |
Sum() | Adds the total of all numeric values in a field |
It's important to note that SQL's aggregate functions are not the same as CFML functions, about which you learn more in the next chapter.
![]() |
Take a look at the three queries in the latter half of the page. Each is designed to count the database entries for a candidate. They use a SQL aggregate function called count to see how many records include a response field containing a given candidate's name. You always use count with parentheses containing the name of the table field you want to count. You'll find more information on SQL's aggregate functions in the sidebar accompanying this chapter.
Following count(response) are the words as total, which is a SQL alias. An alias is simply a way of giving something a temporary name that's often more convenient than its actual name. For example, if your table includes an extremely long field name, you would use a query similar to the following to save a lot of text farther down the page:
<cfquery name="get_employee" datasource="some_datasource"> select people_in_the_accounting_department_first_and_last_name as name from employees </cfquery>
Although the actual database field is named people_in_the_accounting_department_first_and_last_name, the query shown in the preceding example creates an alias called name. If you were to use the results of this query in a <cfoutput> section later, you would use the alias rather than the long name, as the following example demonstrates:
<cfoutput query="get_employee"> #name# </cfoutput>
The poll example uses the alias name total so that you can later refer to a candidate's vote count by using the format [query_name].total:
#get_mickey.total#
Now that you're more familiar with the new elements in Listing 49-2, you are ready to review the program flow. When a user visits the page the first time, no action variable is present, so <cfparam> creates one and sets it to an empty, dummy value. The first <cfif> condition states that if action is anything other than go, display the form, as shown in Figure 49-5.
Figure 49-5: The output of question1.cfm when no action is passed
The form is a fairly standard one except that its action attribute points back to this same page, question1.cfm. It also includes a hidden field, action, which is set to go. When a user chooses a candidate and submits a form, action=go is passed along with the candidate information. This triggers the second half of the <cfif> statement, rather than the first.
In the <cfelse> section, the page first inserts the user's candidate selection into the response table. Then it performs three queries to count the number of votes currently recorded for each candidate. Finally, it displays the user's selection and the current standings for each candidate, as shown in Figure 49-6.
Figure 49-6: The output of question1.cfm when action is "Go"
Tip | The action page question1.cfm uses three distinct queries to count the number of votes for each candidate. This method was used to illustrate the use of program flow. However, know that there's a much more efficient method--SQL's GROUP BY clause. Use of this clause goes beyond the space available in this chapter, but you'll find more about it in any SQL reference or Microsoft Access' help files. |
| < Day Day Up > |
|