Download Active using asp (Active Server Pages)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Database wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Oracle Database wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

SQL wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Clusterpoint wikipedia , lookup

PL/SQL wikipedia , lookup

Database model wikipedia , lookup

Relational model wikipedia , lookup

Transcript
PL
Crudding with ColdFusion
i
'Crudding' with ColdFusion
by
Peter Lake and Hugh Lafferty
PL
Crudding with ColdFusion
i
PL
Crudding with ColdFusion
ii
Table of Contents
1.
Introduction .................................................................................................................................... 1
1.1. Assumptions about the reader ................................................................................................... 2
1.2. How to use these notes ............................................................................................................. 2
1.3. Recordset .................................................................................................................................. 2
1.4. Database Connections ............................................................................................................... 3
1.5. Data Source Names (DSNs) and opening connections ............................................................. 3
1.6. Executing SQL ......................................................................................................................... 3
2. Hello world ...................................................................................................................................... 4
3. A first go at dynamic ColdFusion Markup Language ................................................................. 5
4. Passing Parameters to URLs ......................................................................................................... 7
5. Using the CFForm ........................................................................................................................ 10
6. Using the CFGrid in Read Only mode ........................................................................................ 12
7. Using the CFGrid to delete from the database ........................................................................... 14
8. Conditional processing ................................................................................................................. 16
9. Back to updating from a Grid ..................................................................................................... 17
10.
References ................................................................................................................................. 19
10.1.
Books .................................................................................................................................. 19
10.2.
Web-sites ............................................................................................................................ 19
11.
Self-Test ..................................................................................................................................... 20
12.
Tutorial ...................................................................................................................................... 21
13.
Solutions to b Activities ............................................................................................................ 22
14.
Appendix A................................................................................................................................ 26
PL
Crudding with ColdFusion
ii
PL
Crudding with ColdFusion
1
1. Introduction
ColdFusion acts as an extension to a Web Server, in much the same that ASP works. As we shall see
the platform is irrelevant as the ColdFusion server is an in-RAM service which can be set up to
communicate via APIs with whichever Web Server is running on the physical server.
The job of the Web Server, such as Apache or IIS, is to return HTML to a client as a result of a URL
request from that client. ColdFusion is a tag-based language that can be incorporated into an HTML
page. When the webserver sees a <CF> tag it calls on the CodFusion server and asks it to act on the
tag. CF will return some HTML which the webserver can then parcel up with any other HTML on the
URL template and return to the requester. Actually the term ColdFusion server is rather misleading as
the functionality is actually contained in a DLL that is called as a module by Apache.
In this way, ColdFusion can act as an intermediary between the Webserver and a database. For
example the <CFQuery> tag that we shall use extensively in what follows gets passed to ColdFusion
Server to deal with. ColdFusion will then query the datasource and return the output. That output is
then available as output in HTML format.
In what follows we use a text editor and an FTP client. There are other tools available. Dreamweaver,
for example, offers a friendly IDE for the entire website development cycle. We use the word Put to
mean "use FTP to send to the server". If you do not have Dreamweaver you could just as easily use a)
TextPad (switch line numbering on), and b) WSFTP. If you do not know how to use an FTP client,
then look at the accompanying "How to FTP" notes.
'Crudding' is a shorthand for "Creating Updating and Deleting" and we include Browsing into
crudding. So, we then move on to show how to Browse a file, Create records in a file, Update records
in a file and Delete records from a file.
In the examples in this document we will be using the SHU Oracle instance, which is running on a
database server called Ivy, and the CMS application server, which is called Pertinax. Refer to separate
notes on using Ivy.
The Oracle database and RDBMS (Relational Database Management System) is a database engine
which allows many users to have accounts which are referred to as schema. The owners of accounts
can store data in tables in their schema. They can grant access to the tables to other users. They can
create new tables, insert data into their tables, update (change) the data, and they can delete the tables
or the data therein.
Registered students at SHU can create an account for themselves on the Oracle Database used for
teaching. More information about using Oracle at SHU (including how to create your account) can be
seen at: http://oracledocs.shu.ac.uk/Local/GetStarted/getstarted.ppt
In some of the examples in these notes we access the data in some tables owned by an Oracle user
called SCOTT. Your schema has been granted the privilege of "select" on the tables belonging to the
schema "scott". Thus the table to be queried is referred to as "scott.emp" meaning scott's emp table.
PL
Crudding with ColdFusion
1
PL
Crudding with ColdFusion
1.1.
2
Assumptions about the reader
We have made a number of assumptions about the reader of these notes, and these are



1.2.
You are already a competent programmer (so we will not bother explaining what a variable is)
You know what a Web server is. If not please refer to the accompanying "Web Server" notes
You know how to FTP. If not please refer to the accompanying "How to FTP" notes
How to use these notes
Many of the activities are numbered with an a or a b extension e.g. Activity 2a.
If these notes are delivered in face-to-face mode with students who have a computer in front of them
then we would expect the lecturer to demonstrate the a Activity and highlight any teaching points, and
then ask the students to simply copy that exercise. Having these notes in electronic form makes
copying very easy. However, this could lead to students simply copying and not understanding. That is
why the b activities are included. If time permits the students should then practice the ideas in the
associated b Activity with the lecturer going round helping. If time does not permit then the students
should, in their own time, do the b activities. Before the next lecture students should do the Tutorial
and in the next lecture the lecturer could run a quiz based on the Self-Test section.
If these notes are used in distance-learning mode then simply go through them in order, first of all
copy each a Activity and note carefully the teaching points, then try out the b Activity. Then do the
Tutorial, and then try the Self-Test. When you come back to these notes read the Summary first to see
if you have remembered all the points in there.
1.3.
Recordset
One important concept in these notes is the idea of a Recordset, which is a copy, normally held in
client RAM, of a table or results of a query. It is best thought of as a rectangular structure with rows
corresponding to records and columns corresponding to fields, exemplified below
Customer
CustomerNo
CustomerTitle
Record 1
Record 2
Record 3
CustFirstName
CustSurname
ColdFusion takes care of Recordsets for you. They are automatically created as a result of a
CFQUERY. You can either display the resultant recordset using a vanilla <CFOUTPUT> tag, or
manipulate it by adding attributes like MAXROWS and STARTROW to the <CFOUTPUT> tag. More
of that later.
PL
Crudding with ColdFusion
2
PL
Crudding with ColdFusion
1.4.
3
Database Connections
In order to create a recordset ColdFusion must first be able to connect to a database.
Pertinax has IIS webserver installed, with the ColdFusion module enabled. This means that you can
store files on Pertinax with a .CFM extension and include ColdFusion tags in those documents.
Pertinax also already has a data source set up, pointing at the SHU92 Oracle instance on Ivy.
Once you have created your templates locally you will need to upload, using FTP, into your area on
Pertinax. If you were using dldb1, as all the following examples do, once you have ftp’ed your files to
Pertinax you can get to them from the web by pointing to a URL like:
http://pertinax.cms.shu.ac.uk/pg/dldb/dldb1/opening1.cfm
The upside is that your data source is already set up. The downside is that you need to provide your
Oracle login and password to ColdFusion to give it access to your schema objects. Not the most secure
way of doing it, but it serves to demonstrate how the technology hangs together.
1.5.
Data Source Names (DSNs) and opening connections
A Data Source Name (DSN) is a pointer to a database. This pointer is an ODBC System DSN and must
have been set up by a system administrator and can point to a database anywhere in the world.
At Sheffield Hallam University there are a number of servers and students are often provided space for
their CFM pages on a server called Pertinax and space for Oracle databases on a server called Ivy, and
so we have this set up
Pertinax
cfm
pages
Ivy
Oracle
DSNs
s
1.6.
Executing SQL
We now have the important elements of a ColdFusion database query in place. There just remains
the question of how we query the database. This is done using a standard SQL string. The
<CFQUERY> tag has a number of attributes (see example below), amongst them are the ODBC
datasource we will be using, our Oracle username and password, and then, the actual SQL query.
<cfquery name="emplist" datasource="shu92" username="cmspl4" password="murph">
select * from scott.emp
</cfquery>
Don’t forget to use
your own Oracle
username and
password instead
of cmspl4
PL
Crudding with ColdFusion
3
PL
Crudding with ColdFusion
4
2. Hello world
ACTIVITY 1a. The objective of this exercise is to make sure that you can get a simple, static
CodFusion page to work. It will be deeply uninteresting if you are used to writing HTML. The main
objective is to demonstrate that ColdFusion documents MUST contain HTML.
Using a text editor to construct the following, and save as welcome.cfm. Put it to a server and then
call it in a browser using something like
http://pertinax.cms.shu.ac.uk/pg/dldb/dldb1/Hello.cfm
Use your own nn
HTML>
<HEAD>
<TITLE> CF Page </TITLE>
</HEAD>
<BODY>
<cfset welcomemess = "This Welcome come to you from inside a CFOUTPUT tag">
<cfoutput>
#welcomemess#
</cfoutput>
</BODY>
</HTML>
We have used the CFSET tag to declare a string variable. In order to display CF Variables, you need to
display from within a CFOUTPUT tag pair. Note the use of the # around CF variables.
ACTIVITY 2b. Create a file called MyMessage.cfm that displays on the client a message other than
this one. Save it to a server and call it from a browser. You should thus have practiced a) creating a cfm
page on a development machine b) FTP-ing the cfm page to a server c) Calling the cfm page from a
browser on a client.
You should rehearse in your mind what the sequence of events is when you type something like
http://pertinax.cms.shu.ac.uk/mmtec/mmnn/ Hello.cfm in a browser.
The teaching points from those exercises were



cfm pages are written inside HTML pages
cfm code is interpreted by a cfm extension to a web server (e.g. IIS, Apache, Tomcat)
the cfm extension simply passes back any HTML (and anything inside <SCRIPT> tags) back
to the web server
However, as we shall see in a minute, if the extension sees an SQL statement then it has to
converse with the database using whatever drivers that it has been told to use, and eventually send
back dynamically created HTML to the web server.
PL
Crudding with ColdFusion
4
PL
Crudding with ColdFusion
5
3. A first go at dynamic ColdFusion Markup Language
The example in 1.6 is a good start. With it we can create a recordset which in this case would look
something like this output from sqlplus:
ACTIVITY 3a. The objective of this activity is to List the contents of one column in a table on the
server
We will use a very similar query to 1.6, with the main difference that we restrict the select to one
column; ename. We will then simply display that column from the resultant recordset. To try this out,
cut and paste this code into a new file, using an editor like TextPad. Save the file as emp1.cfm. Then
PUT the file onto your Pertinax account using FTP.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<cfquery name="emplist" datasource="shu92" username="cmspl4" password="murph">
select ename from scott.emp
</cfquery>
Again, don’t forget
<html>
to use your own
ColdFusion Tags
<head>
Oracle username
<title>Employees</title>
and password
</head>
instead of cmspl4
<body bgcolor="silver">
<CFOUTPUT query="emplist">
#ename#
</CFOUTPUT>
</body>
</html>
Ordinary
HTML
tags
PL
Crudding with ColdFusion
5
PL
Crudding with ColdFusion
6
Now the exciting bit. Launch your browser and point it at your URL on Pertinax. And, with a bit of
luck, we will have our first dynamically created web page, looking like this:
So, OK, the format isn't much to write home about, but just think what has happened here. If another
user adds to, or deletes from the EMP table and you revisit the URL, the list will automatically alter to
match the database.
ACTIVITY 3b. Write a CFM page that displays, in a list, the distinct job titles that exist in the EMP
table. They should be centred on the screen. Hint: use the <DIV align=center> HTML tag within the
CFOUTPUT .
The teaching points from those exercises were
o
o
o
o
o
o
PL
To specify what data should be retrieved into a recordset, use a SQL select within the
CFQUERY tag
When ColdFusion is passed this tag it sends the SQL string to the indicated datasource. The
results are not displayed automatically, but come back as a recordset
The column names are returned as variables that you can use how you like
To output field names from the recordset use the format: #columnname#
Actually, the hashes are used to enclose any CF Variable. You will use variables later, but in
this case ColdFusion has automatically declared the columnnames as variables.
#variablename# only gets translated into its value if placed within a CFOUTPUT
Crudding with ColdFusion
6
PL
Crudding with ColdFusion
7
4. Passing Parameters to URLs
ACTIVITY 4a. The objective of this activity is to pass information to a second form and allow
ColdFusion to access that data to refine a SELECT.
So far one page, and one bit of information. Now let's see if we can let the user select one of the listed
employees from 3a, and take them to a second page which contains details about where that employee
works. We will use a standard HTML anchor, and pass the required employee number to the second
page through the URL.
Paste the following code into a file called Act3a.cfm, alter username and password, and PUT it onto
Pertinax.
This is a
standard
HTML
anchor, but
note how the
value of
#ename# is
what gets
displayed
because its
within a
CFOUTPUT.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<cfquery name="emplist" datasource="shu92" username="cmspl4" password="murph">
select empno, ename from scott.emp
</cfquery>
Note that we need the recordset to
<html>
include both columns, even though
<head>
we are only displaying the name
<title>Employees</title>
</head>
<body bgcolor="silver">
<b>Please select from the list of Employees:</b>
<P></P>
The employee number
<cfoutput query="emplist">
for the person selected
<li>
by name gets passed as a
<DIV>
<a href="EmpDetails.cfm?sel_emp=#empno#"> URL parameter
#ename#</a>
</DIV></li>
</CFOUTPUT>
</body>
</html>
PL
Crudding with ColdFusion
7
PL
Crudding with ColdFusion
8
Now point your browser at this new URL. It should look something like this:
Now we need to create EmpDetails.cfm.
TIP: There is a join involved in generating the required recordset. When the SQL becomes complex
you might find it easier to develop and test the SQL, for example in SQLPLUS, first, so that you know
that the SQL string within the CFQUERY will work.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<cfquery name="empdet" datasource="shu92" username="cmspl4" password="murph">
select empno, ename, dname, loc from scott.emp a, scott.dept b
where a.empno=#url.sel_emp#
and a.deptno=b.deptno
Note how we
Yes, we can do
</cfquery>
use the
joins!
<html>
sel_emp
<head>
variable as
<title>Employee Details</title>
passed in the
</head>
URL
<body bgcolor="silver">
<b>Details for selected employee:</b>
<P></P>
<cfoutput query="empdet">
REF: #empno#, <BR>
NAME: #ename#, <BR>
Department: #dname#, <BR>
Based: #loc#
</CFOUTPUT>
</body>
</html>
PL
Crudding with ColdFusion
8
PL
Crudding with ColdFusion
9
ACTIVITY 4b. Build upon your Activity3b work and create a CFM page that displays, in a list, the
distinct job titles that exist in the EMP table as anchors. When the user clicks one, it should move to
another page that lists all the employees who work in that role.
Hint: If you are using a string in your select, the database will expect to see a single quote around the
value, for example: where ename='#sel_name#'. You must note put quotes round numbers, however.
The teaching points from those exercises were
o
o
o
o
o
o
PL
The SQL string can contain complex SQL statements
If a value has been passed to a page through the URL, ColdFusion gives you access to it like
any other variable by prefixing "URL." in front of the variable name.
When you use the URL prefix, you are specifying the scope of the variable. More of this later
You can pass multiple URL variables in this way.
We will find that this sort of prefix is used often. Amongst others, we can declare variables as:
o cookie.variablename
o form.variablename
o session.variablename
o client.variablename
These are all ways of dealing with the stateless problem inherent in using web pages. Cookies
store information client-side. Form variables are passed to the called form from the calling
form. The other two store information server-side. In fact, ColdFusion deals with client
management, by default, using the registry. To make applications more scaleable, this can be
changed to use an ODBC database.
Crudding with ColdFusion
9
PL
Crudding with ColdFusion
10
5. Using the CFForm
ACTIVITY 5a. The objective of this activity is to improve the look and feel of the user interface
using CFFORM
We have thus far only listed our data out using traditional HTML code. ColdFusion comes with some
data presentation tags which can really improve the look of a template. If you are familiar with an
HTML Form, the usage will look familiar, with ACTION indicating where the template should move
to when the user presses SUBMIT.
From within CFForm tag pair we will have access to other display control tags. In this example we use
a CFSELECT to provide the user with a rather smarter list than a mere set of anchors. This is what we
are aiming for:
PL
Crudding with ColdFusion
10
PL
Crudding with ColdFusion
11
And here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<cfquery name="emplist" datasource="shu92" username="cmspl4" password="murph">
select empno, ename from scott.emp
</cfquery>
<html>
<head>
<title>Employees</title>
</head>
<body bgcolor="silver">
<P align=center><FONT size=5><b>The Dacotta Company Employee List</b></FONT></P>
<P align=center><FONT size=5><B><IMG alt="" border=0 height=129
src="dacotta.jpg" style="HEIGHT: 140px; WIDTH: 240px"
width=153></B></FONT></P>
<P>
<HR width=500>
CFSELECT
within a
CFFORM
What value
in the
recordset to
pass as a
variable to
the next
Form when
submitted
<P></P>
<P align=center><STRONG>The following employees work for The Dacotta Co.:</STRONG></P>
<P></P>
<P align=center>
<cfform action="EmpDetails2.cfm" method="POST" enablecab="Yes">
<cfselect name="selemployee"
As with an HTML Form, the action
SIZE="#emplist.recordcount#"
indicates the template to move to when
message="You must select an employee to continue"
query="emplist"
the user SUBMITS
value="empno"
display="ename"
Note the automatically created cf variable which
required="Yes">
tells you how many records are in the recordset
</cfselect>
<P align=center><input type="Submit" value="View Details"></p>
</cfform>
</P>
</body>
</html>
Make sure you understand what the other attributes of the CFSELECT do by experimenting with this
code. Note that we have altered EmpDetails.cfm that we created in Activity 4a to accept a value from a
Form scoped variable, instead of a URL. The change is a line that now reads:
where a.empno=#form.selemployee#
instead of:
where a.empno=#url.sel_emp#
Other input tags include CFTEXTINPUT, CFSLIDER, and as we shall see later, CFGRID.
ACTIVITY 5b. Build upon your Activity4b work and create a CFM page uses a CFS instead of
anchors.
The teaching points from those exercises were
o
o
o
PL
The CFFORm provides a developer with enhanced display capabilities
CFSELECT allows the user to select from a list
Variables can be passed between CFFORM
Crudding with ColdFusion
11
PL
Crudding with ColdFusion
12
6. Using the CFGrid in Read Only mode
ACTIVITY 6a. The objective of this activity is to display recordset data in a grid using CFGRID
The output we are aiming for is something like a spreadsheet. We will use a grid to both display data,
and to allow the user to select and update data presented therein.
The easiest type of grid is one that is used only for Browsing, in Read Only mode. In the example
below the user can navigate around the grid. They cannot modify any data, and if the CFFORM
containing the grid is submitted, no Grid data is passed on. In the example below we present the user
with the Department details within a grid.
You should be aware, and you should make sure your users are aware, that these tags are actually Java
Applets and, as such, when they are used for the first time on a client machine, there will be an
automatic applet download. On a slow modem this could take 20+ minutes.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<cfquery name="depts" datasource="shu92" username="cmspl4" password="murph1">
select deptno, dname, loc
from scott.dept
</cfquery>
<html>
<head>
<title>Employee Details</title>
</head>
<body bgcolor="silver">
<b>Dacotta Company Departments</b>
<P></P>
<cfform action="handle_grid.cfm" method="POST" enablecab="Yes">
<!--- CFGRID with all setting as default --->
Provide the user
with buttons to
sort the data
<cfgrid name="" align="MIDDLE" query="depts" insert="No" delete="No" sort="Yes"
colheaders="Yes" colheaderalign="LEFT" colheaderbold="Yes" selectmode="BROWSE"
>
</cfgrid>
</cfform>
</body>
</html>
Check out the online ColdFusion reference for a description of the attributes.
PL
Crudding with ColdFusion
12
PL
Crudding with ColdFusion
13
The user should see something like this:
Note how the column widths have defaulted to just wide enough to display the column headings.
Within a CFGRID, you can take control of the Rows and Columns with the CFGRIDROW and
CFGRIDCOLUMN tags.
Here we have fixed the column width. Measured in pixels. Note also that we are displaying Deptno. It
is not always the case that we want to display all columns to the user. Sometimes we still need to return
the value because we want to pass the row data to the next form, particularly if that value is a primary
key, but want the user to be unaware of its value. Finally, we have Selectmode set as ROW, which
means that clicking on the row highlights it and makes the values available in the form variable
#gridname.columname#
Everything else as before……
<cfgrid name="" align="MIDDLE" query="depts" insert="No" delete="No" sort="Yes"
colheaders="Yes" colheaderalign="LEFT" colheaderbold="Yes" selectmode="ROW">
<CFGRIDCOLUMN NAME="dname" HEADERBOLD="Yes" Width="100">
<CFGRIDCOLUMN NAME="loc" HEADERBOLD="Yes" HEADER="Location" Width="80">
<CFGRIDCOLUMN NAME="deptno" HEADERBOLD="Yes" Display="No">
</cfgrid>
Everything else as before……
PL
Crudding with ColdFusion
13
PL
Crudding with ColdFusion
14
ACTIVITY 6b(i)
Experiment with the attributes in both CFGRID, CFGRIDCOLUMN and
CFGRIDROW.
ACTIVITY 6b(ii)
You have now had experience of using CFGRID and CFSELECT. Use the
online documentation to see what other CFFORMS related tags there are. Try some out.
The teaching points from those exercises were
o
o
o
o
o
CFGrid has much built-in functionality to enable users to view, select and amend records
Browse = "Edit" is required if you want let the users insert, update or delete
To enable users to delete, set the delete= attribute to "YES" and the selectmode to "Edit".
BE AWARE, users edit only the entries in the grid, which is a recordset, probably in their
RAM. You will need to process their changes if you want them reflecting in the database.
As this functionality is enabled using Java applets, be aware that a target client machine must
be Java enabled, and be prepared for a lengthy download the first time they use one of the
controls.
7. Using the CFGrid to delete from the database
ACTIVITY 7a. The objective of this activity is to reflect changes made to the locally held recordset
displayed in a CFGRID back to the database.
Remember that what is being displayed in a grid is only a copy of data from a database. Even if we set
the Selectmode to EDIT and have both INSERT and DELETE = "YES", we are only allowing the user
to amend the their recordset. We need to find some way to reflect back any changes to the database.
One simple way is a tag called CFUPDATEGRID. However, this has several limitations for all but
simple, single table scenarios, so we will go straight to using CFQUERY to do this, as we will then be
able to cope with any eventuality in the future.
The basic principle is that when a CFGRID gets submitted, the receiving template has access to 3
arrays:



#Form.gridname.columnName[rowindex]# holds the new values for a particular column
#Form.gridname.Orininal.columnName[rowindex]# holds the old values for a particular column
#Form.gridname.RowStatus.Action[rowindex]# stores the type of change to a row. U, for Update,
D for Delete, I for insert.
With this information we can determine exactly what has been changed and then write a SQL statement
to reflect those changes back to the database.
Up until now we have been using SCOTT's tables. We don’t have write access to these tables. For this
exercise you need to create your own table in your schema. Scripts for creating sample tables with
some data are appended to these notes.
PL
Crudding with ColdFusion
14
PL
Crudding with ColdFusion
15
To start with we will simply write some code to delete a record that the user has selected. This is not
very useful, but illustrates the principles involved. In the next section we discover how to use
conditional processing in ColdFusion, and when we have those skills we will revisit our grid update
requirements.
Building on the work we did in Activity 6a, we here have added an HTML submit button.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<cfquery name="CDs" datasource="shu92" username="cmspl4" password="murph1">
select Catalogue_Number, Title, Daily_Cost
from CD
</cfquery>
<html>
<head>
<title>CD Masterfile</title>
</head>
<body bgcolor="silver">
<b>All CDs in the Collection</b>
<P></P>
The template that will get called when
the user presses the submit button
<cfform name="GridForm" action="Act7a2.cfm" method="POST" enablecab="Yes">
<!--- CFGRID with all setting as default --->
<cfgrid name="CDGrid" align="MIDDLE" query="CDs" insert="No" delete="No" sort="No"
colheaders="Yes" colheaderalign="LEFT" colheaderbold="Yes" selectmode="ROW">
<CFGRIDCOLUMN NAME="Title" HEADERBOLD="Yes" Width="150">
<CFGRIDCOLUMN NAME="Daily_Cost" HEADERBOLD="Yes" HEADER="Cost per Day"
DataAlign="Right" Width="80">
<CFGRIDCOLUMN NAME="Catalogue_Number" HEADERBOLD="Yes" Display="No">
</cfgrid>
<INPUT TYPE=submit value="Delete Selected"></p>
Select a CD before pressing Delete
</cfform>
</body>
</html>
Now we need to create the template to handle the submitted data. Paste this into Act7a2.cfm and PUT
it onto Pertinax:
<HTML>
<HEAD>
<TITLE>Delete the selected CD</TITLE>
</HEAD>
<BODY>
<cfoutput>
<H3>Deleting #form.CDGrid.Title# from the database</H3>
</cfoutput>
<cfquery name="CDdel" datasource="shu92" username="cmspl4" password="murph1">
delete from CD where Catalogue_Number=#form.CDGrid.Catalogue_Number#
</cfquery>
--->
Record Deleted
The values of the
</BODY>
selected row are passed
</HTML>
as CF variables.
Of course this is a very simple application. It is one table, and we are sure that we can uniquely identify
the record to be deleted because we included the primary key in the recordset. But the CFQUERY
could be any legitimate SQL, as we will see later.
PL
Crudding with ColdFusion
15
PL
Crudding with ColdFusion
16
ACTIVITY 7b(i)
Create a table in your schema which will record a CD selection. It should
have one field, called selectedcd in which you can store catalogue_numbers. Call the table
SELECTIONS.
ACTIVITY 7b(ii)
Save Ac7a.cfm as Act7b.cfm and change the button to say "Add to Basket".
Don’t forget to change the Action as you should save Act7a2.cfm as Act7b2.cfm. Make this latter
template issue a SQL command to insert the selected Catalogue_Number into the SELECTIONS table.
The teaching points from those exercises were
o
o
o
o
The Action attribute tells us which template will be used when the user submits.
Grid values are passed to the called template on submission.
That called template can be used to interact with the database.
In this way, as we will see, we can keep the CFGRID and database in step.
8. Conditional processing
ACTIVITY 8a. The objective of this activity is to demonstrate how conditional processing is enabled
with CF tags.
The <CFIF> tag allows us to test for some condition an decide how to act dependant upon the value.
These conditions can be expanded using the <CFELSEIF>. The block needs ending with a </CFIF>.
There is also a <CFSWITCH><CFCASE> construct for more complex conditional processing.
In our first example we can begin to make our forms more robust. In this case we do so by checking
that our recordset has returned some values before we display the CFGRID and button. If there are no
records, we display a message to the user:
Up to here, the same as 7a……
<cfif #CDs.recordcount# greater than 0>
<!--- Some values, so make this into a cfform to enable us to use the cfgrid --->
<cfform name="GridForm" action="DelForm.cfm" method="POST" enablecab="Yes">
<!--- CFGRID with all setting as default --->
<cfgrid name="CDGrid" align="MIDDLE" query="CDs" insert="No" delete="No" sort="No"
colheaders="Yes" colheaderalign="LEFT" colheaderbold="Yes" selectmode="ROW">
<CFGRIDCOLUMN NAME="Title" HEADERBOLD="Yes" Width="150">
<CFGRIDCOLUMN NAME="Daily_Cost" HEADERBOLD="Yes" HEADER="Cost per Day"
DataAlign="Right" Width="80">
<CFGRIDCOLUMN NAME="Catalogue_Number" HEADERBOLD="Yes" Display="No">
</cfgrid>
<INPUT TYPE=submit value="Delete Selected"></p>
Select a CD before pressing Delete
</cfform>
<cfelse>
<!--- No data return from query --->
<font size="+1"><i>No CDs found, contact your administrator</i></font>
</cfif>
…………..from here, the same as 7a
PL
Crudding with ColdFusion
16
PL
Crudding with ColdFusion
17
There are other flow control tags. Check out the online reference.
ACTIVITY 8b. Build upon your Act4b work to make sure that the list of Jobs only gets displayed the
recordset contains some records. Try the <CFSWITCH> control.
The teaching points from those exercises were
o
o
CFIF structure gives us control over our processing
There are other useful flow control tags
9. Back to updating from a Grid
ACTIVITY 9a. The objective of this activity is to demonstrate how to reflect all the changes from a
CFGRID in the underlying database.
We are not using anything here that is all that new, just a bit more complex. Try and follow the code
and make sure you understand what is happening.
Those of you new to Oracle will be surprised that there is no such thing as an autoincrement field.
Actually, the thing you use is more powerful, and is called a sequence. It’s a schema object that you
will need to create using this syntax:
CREATE SEQUENCE NEWCD INCREMENT BY 1 START WITH 1 ;
We can now call that sequence whenever we need the next number, in effect giving us the same as an
autoincrement.
The process that Act9a2.cfm goes through is to loop through all the rows passed to it from the
submitting form (Act9a.cfm) and check what activity has been carried out on each row. We then use
our conditional processing to run the appropriate SQL command.
Up to here, the same as 8a……
<cfif #CDs.recordcount# greater than 0>
<!--- Some values, so make this into a cfform to enable us to use the cfgrid --->
<cfform name="GridForm" action="Act9a2.cfm" method="POST" enablecab="Yes">
<!--- CFGRID with all setting as default --->
Let the user do
their worst!
<cfgrid name="CDGrid" align="MIDDLE" query="CDs" insert="YES" delete="YES" sort="No"
colheaders="Yes" colheaderalign="LEFT" colheaderbold="Yes" selectmode="EDIT">
<CFGRIDCOLUMN NAME="Title" HEADERBOLD="Yes" Width="150">
<CFGRIDCOLUMN NAME="Daily_Cost" HEADERBOLD="Yes" HEADER="Cost per Day"
DataAlign="Right" Width="80">
<CFGRIDCOLUMN NAME="Catalogue_Number" HEADERBOLD="Yes" Display="No">
</cfgrid>
<INPUT TYPE=submit value="Commit Changes to Database"></p>
</cfform>
…………..from here, the same as 8a
PL
Crudding with ColdFusion
17
PL
Crudding with ColdFusion
18
And then the processing template:
<HTML>
<HEAD>
<TITLE>Deal with submitted grid values</TITLE>
</HEAD>
<BODY>
<H3>CD row updates</H3>
<CFIF IsDefined("form.CDgrid.rowstatus.action")>
Useful CF function which returns TRUE if the named
variable exists. In this case the processing wont happen if
you directly call Act9a2.cfm from your browser, because the
grid on the calling Act9a will not have been defined.
<CFLOOP INDEX = "Counter" FROM = "1" TO =
#ArrayLen(form.CDGrid.rowstatus.action)#>
Loop through every altered row submitted
<CFOUTPUT>
The row action for #Counter# is:
#form.CDGrid.rowstatus.action[Counter]#
<BR><BR>
</CFOUTPUT>
Check whether Delete, Update or Insert
<CFIF form.CDGrid.rowstatus.action[Counter] IS "D">
<cfquery name="CDDel" datasource="shu92" username="cmspl4" password="murph1">
delete from CD where Catalogue_Number=#form.CDGrid.original.Catalogue_Number[Counter]#
</cfquery>
<CFELSEIF form.CDGrid.rowstatus.action[Counter] IS "U">
<cfquery name="CDUpd" datasource="shu92" username="cmspl4" password="murph1">
UPDATE CD
SET Title = '#form.CDGrid.Title[Counter]#' ,
Daily_Cost = #form.CDGrid.Daily_Cost[Counter]#
WHERE Catalogue_Number=#form.CDGrid.original.Catalogue_Number[Counter]#
</cfquery>
<CFELSEIF form.CDGrid.rowstatus.action[Counter] IS "I">
<!--- note: requires a sequence called newcd, created thus:CREATE SEQUENCE NEWCD INCREMENT BY 1 START WITH 1 ;--->
<cfquery name="CDIns" datasource="shu92" username="cmspl4" password="murph1">
INSERT into CD
Values( newcd.nextval ,'#form.CDGrid.Title[Counter]#' , #form.CDGrid.Daily_Cost[Counter]#)
</cfquery>
</CFIF>
</CFLOOP>
</CFIF>
</BODY>
</HTML>
ACTIVITY 9b Just spend some time understanding what we have just done! It's quite complex, but
in understanding that we are ready for more or less anything!
The teaching points from those exercises were
o
PL
We can keep the CFGRID and database in step!
Crudding with ColdFusion
18
PL
Crudding with ColdFusion
10.
19
References
10.1.
Books
Danesh & Motlagh, Mastering ColdFusion 4.5, Sybex. This weighty tome has much to commend it.
10.2.
Web-sites
Online CFML Language Reference
ColdFusion Forum at Macromedia
PL
Crudding with ColdFusion
19
PL
Crudding with ColdFusion
11.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
PL
20
Self-Test
What is a Recordset?
How do you connect to a server?
How do you create a Recordset?
How do you send the information from a Recordset to a database?
How do you call one cfm page from another cfm page?
How can values be passed between cfm pages?
Why might using a URL parameter not be the most secure method of answering 6?
What tag do we use to run some SQL against our Oracle database?
Which tags allow us to process conditionally?
When a user deletes a row is the change reflected automatically in the database?
How do you find out how many rows there are in a recordset?
How do you find out if a CF variable is defined?
What tag would you use to alter the heading of a Grid column?
What is a DSN?
How are DSNs set up?
Dreamweaver MX makes much easier the production of much of the code that we have produced
here. Discuss whether this lecture has been a waste of time.
Crudding with ColdFusion
20
PL
12.
Crudding with ColdFusion
21
Tutorial
Build on the work we did with the CD table to get the system to register that a customer has taken a CD
on loan. They log on, select CDs and then log off. The CDs are sent later in the post. Lets make life
simple for the time being and make a rule that only existing customers can use the system and that they
can only make one new loan per day. This allows us to make assumptions about what primary keys
should be used to record loans.
a) Create a Customer Table which should contain customer identifier, name, address and password.
b) Alter the SELECTIONS table so that it records a customer ID, a CD ID and a loan date. Think
about what you should use as primary keys, and whether you should have foreign keys. Refer back
to the LDS notes for help on keys.
c) Build a ColdFusion template which asks the user to type in their name and password. HINT:
CFINPUT TYPE="password"
d) Only if the name exists and the password is correct should they be moved on to the next template
e) On that template they should be able to browse, select a row, and then hit a button to order a CD
f) Their selection should get recorded in the SELECTIONS table
Of course, this is just the beginnings of a system, but there is plenty to be going on with there, and lots
of learning to be had!
PL
Crudding with ColdFusion
21
PL
13.
Crudding with ColdFusion
22
Solutions to b Activities
Solution 2b:
<HTML>
<HEAD>
<TITLE> CF Page </TITLE>
</HEAD>
<BODY>
HELLO WORLD
</BODY>
</HTML>
Solution 3b:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<cfquery name="joblist" datasource="shu92" username="cmspl4" password="murph1">
select distinct job from scott.emp
</cfquery>
<html>
<head>
<title>Employees</title>
</head>
<body>
<cfoutput query="joblist">
<DIV align=center>#job#
</DIV>
</CFOUTPUT>
</body>
</html>
PL
Crudding with ColdFusion
22
PL
Crudding with ColdFusion
23
Solution 4b1:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<cfquery name="joblist" datasource="shu92" username="cmspl4" password="murph1">
select distinct job from scott.emp
</cfquery>
<html>
<head>
<title>Employees</title>
</head>
<body>
<cfoutput query="joblist">
<DIV>
<li>
<a href="Act4b2.cfm?sel_job=#job#">
#job#</a>
</DIV></li>
</CFOUTPUT>
</body>
</html>
Solution 4b2:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<cfquery name="empdet" datasource="shu92" username="cmspl4" password="murph1">
select empno, ename from scott.emp
where job='#url.sel_job#'
</cfquery>
<html>
<head>
<title>Employees work as selected job</title>
</head>
<body bgcolor="silver">
<cfoutput>
<!--- need to use cfoutput to display the value in sel_job --->
<b>All employees in the role of #url.sel_job#:</b>
</CFOUTPUT>
<!--- now the repeated output --->
<cfoutput query="empdet">
<P></P>
REF: #empno#, NAME: #ename# <BR>
</CFOUTPUT>
</body>
</html>
PL
Crudding with ColdFusion
23
PL
Crudding with ColdFusion
24
Solution 7bii template one:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<cfquery name="CDs" datasource="shu92" username="cmspl4" password="murph1">
select Catalogue_Number, Title, Daily_Cost
from CD
</cfquery>
<html>
<head>
<title>CD Masterfile</title>
</head>
<body bgcolor="silver">
<b>All CDs in the Collection</b>
<P></P>
<cfform name="GridForm" action="Act7b2.cfm" method="POST" enablecab="Yes">
<!--- CFGRID with all setting as default --->
<cfgrid name="CDGrid" align="MIDDLE" query="CDs" insert="No" delete="No" sort="No"
colheaders="Yes" colheaderalign="LEFT" colheaderbold="Yes"
selectmode="ROW">
<CFGRIDCOLUMN NAME="Title" HEADERBOLD="Yes" Width="150">
<CFGRIDCOLUMN NAME="Daily_Cost" HEADERBOLD="Yes" HEADER="Cost
per Day" DataAlign="Right" Width="80">
<CFGRIDCOLUMN NAME="Catalogue_Number" HEADERBOLD="Yes"
Display="No">
</cfgrid>
<INPUT TYPE=submit value="Add to Basket"></p>
Select a CD to add to basket
</cfform>
</body>
</html>
PL
Crudding with ColdFusion
24
PL
Crudding with ColdFusion
25
Solution 7bii template two:
<HTML>
<HEAD>
<TITLE>Delete the selected CD</TITLE>
</HEAD>
<BODY>
The create should look like this:<BR>
create table SELECTIONS (cd_id integer);
<cfoutput>
<H3>Adding #form.CDGrid.Title# to the selection table</H3>
</cfoutput>
<cfquery name="CDaddto" datasource="shu92" username="cmspl4" password="murph1">
INSERT into SELECTIONS values(#form.CDGrid.Catalogue_Number#)
</cfquery>
</BODY>
</HTML>
PL
Crudding with ColdFusion
25
PL
14.
Crudding with ColdFusion
26
Appendix A
Scripts for creating Oracle table for chapter 7 onwards.
1. Create table:
Create Table CD( Catalogue_Number Integer Primary Key,
Title Char(30) NOT NULL,
Daily_Cost Number(5,2) ,
Constraint CD_cost CHECK (Daily_Cost Between 0 and 100) ) ;
2. Insert Data
INSERT INTO CD Values(22,'Moody Blues Greatest Hits', 1.00) ;
INSERT INTO CD Values(23,'Hits of the 60s',1.20) ;
INSERT INTO CD Values(24,'Hits of the 70s',1.20) ;
INSERT INTO CD Values(25,'Hits of the 80s',1.50) ;
INSERT INTO CD Values(26,'Hits of the 90s',1.50) ;
INSERT INTO CD Values(27,'ELO Greatest Hits',1.00) ;
INSERT INTO CD Values(28,'Worlds Greatest Opera Arias',0.75) ;
INSERT INTO CD Values(29,'Rock Anthems',1.50) ;
INSERT INTO CD Values(30,'Solo Piano Greats',1.50) ;
INSERT INTO CD Values(31,'Dire Straights Greatest Hits',1.25) ;
PL
Crudding with ColdFusion
26