A DataSet just like VB.Net


This tutorial shows you how to create a "dataset" just like the one in VB.Net
In VB.Net you would create a dataset with "edit" button in an extra column.
Once you click "edit", you get an option to "update", "delete" or "cancel edit mode" 
This is just like a cfgrid tag. Although a cfgrid tag lets you bulk insert, bulk update or bulk delete, the dataset object does it one by one. But cfgrid is slower, and may give users Java errors, depending on their browser settings.


You will need two files for this project;
1. Dataset.cfm
2. UpdateDataset.cfm


Also I am using the "NorthWind" database in SQL Server

DATASET.CFM

<!---------------------------------------------------------------------------------------------------------------
This part is for the errors caught on page 2 "UdateDataSet.cfm"
If the query cannot be executed, <cfcatch> catches the exception, and <cflocation> returns you
to this page with the proper "errorcode" to display the proper message !
If insert/update query is executed, <cflocation> returns you back to this page with the proper
"ErrorCode = a"
--------------------------------------------------------------------------------------------------------------->

<cfif IsDefined('URL.ErrorCode')>
    <cfset a =
"Updates Successful">
    <cfset b =
"Datastore could not be updated">
    <cfset c =
"Could not delete from datastore">
    <cfset d =
"Error occured">
    <h2><cfoutput>#Evaluate(URL.ErrorCode)#</cfoutput></h2>
</cfif>
<!---------------------------------------------------------------------------------------------------------------
Below is a regular "select" query to the NorthWind database. For some reason "Select *" 
statements don't work.
--------------------------------------------------------------------------------------------------------------->

<cfquery name="DataSet" DataSource="NorthWind">
    Select EmployeeId,FirstName, LastName
    From Employees
</cfquery>
<!---------------------------------------------------------------------------------------------------------------
Build your HTML Tables. Use <cfform> tag inside <cfoutput>. This will generate as many 
<cfforms> as there are records.
--------------------------------------------------------------------------------------------------------------->

<table border="1">
    <cfoutput query="DataSet">
    <cfform action="UpdateDataSet.cfm">
    <tr>
<!---------------------------------------------------------------------------------------------------------------
Use a list loop to generate number of columns <td>s listed in your query !
--------------------------------------------------------------------------------------------------------------->
   
<cfloop index="Columns" list="#DataSet.ColumnList#">
<!---------------------------------------------------------------------------------------------------------------
Define the primary key or table index. You define the table index, so you can run your update
statements and use this index in your where clauses
--------------------------------------------------------------------------------------------------------------->

    <cfset TableIndex = DataSet.EmployeeId>
       
<td>
<!---------------------------------------------------------------------------------------------------------------
Now comes the fun part !
When you click "edit" button/hyperlink, it will pass the Table Index value to this conditional output !
Thus when you have an Index, you can generate "textboxes" as given below !
--------------------------------------------------------------------------------------------------------------->

        <cfif IsDefined('URL.Index') and URL.Index eq TableIndex>
            <cfif #Columns# eq "EmployeeId">
<!---------------------------------------------------------------------------------------------------------------
Since you need the TableIndex for update, if you should keep that field readonly. Thus, this can be
used effectively for update or delete query
--------------------------------------------------------------------------------------------------------------->

                <input type="text" name="#Columns#" value="#Evaluate(Columns)#" size="#Len(Evaluate(Columns))#" readonly>
            <cfelse>
<!---------------------------------------------------------------------------------------------------------------
Rest of the values can be in editable textboxes as given below !
--------------------------------------------------------------------------------------------------------------->

                <cfinput type="Text" name="#Columns#" value="#Evaluate(Columns)#" required="Yes" size="#Len(Evaluate(Columns))#">
            </cfif>
        <cfelse>
<!---------------------------------------------------------------------------------------------------------------
Other values that are not returned by TableIndex, should remain displayed on the webpage, 
as below;
--------------------------------------------------------------------------------------------------------------->

            #Evaluate(Columns)#
        </cfif>
        </td>
        </cfloop>
        <td>
<!---------------------------------------------------------------------------------------------------------------
the following block of code, changes the option buttons.
For example when you do not have a URL.Tableindex, the webpage should display the "edit" 
button. When a URL.TableIndex is passed, the buttons displayed should change to "update",
"delete" or "cancel" This is exactly what happens 
--------------------------------------------------------------------------------------------------------------->

        <cfif IsDefined('URL.Index')>
            <cfif IsDefined(
'URL.Index') and URL.Index eq TableIndex>
                <input type="Submit" name="Update" value="Update">
                <input type=
"Submit" name="Update" value="Delete">
<!---------------------------------------------------------------------------------------------------------------
The cancel button is to take you out of "edit mode" just like the VB.Net Dataset object's 
cancel button !
--------------------------------------------------------------------------------------------------------------->
               
<input type="Button" name="Update" value="Cancel" onClick="window.location.href='#CGI.Script_Name#'" id="Button">
            <cfelse>
                <input type="Button" name="Update" value="Edit" onClick="window.location.href='?Index=#TableIndex#'" id="Button">
            </cfif>
        <cfelse>
            <input type="Button" name="Update" value="Edit" onClick="window.location.href='?Index=#TableIndex#'" id="Button">
        </cfif>
        </td>
    </tr>
</cfform>
</cfoutput>
</table>
<!---------------------------------------------------------------------------------------------------------------
Use a little bit of java script for consistency. You can use hyperlinks instead. 
But all buttons or all hyperlinks just looks better and uniform.
--------------------------------------------------------------------------------------------------------------->

UPDATEDATASET.CFM

<!---------------------------------------------------------------------------------------------------------------
I used a cfswitch statements to decide whether to "update" datastore or "delete" from datastore
--------------------------------------------------------------------------------------------------------------->

<cfswitch expression="#Form.Update#">
<!---------------------------------------------------------------------------------------------------------------
If the button on form said "Update" the following block executes to update the database
--------------------------------------------------------------------------------------------------------------->

    <cfcase value="Update">
<!---------------------------------------------------------------------------------------------------------------
try to update the dataset with the update sql statement
--------------------------------------------------------------------------------------------------------------->

        <cftry>
            <cflock timeout=
"30" throwontimeout="No" type="EXCLUSIVE">
            <cftransaction>
                <cfquery name=
"DeleteRow" datasource="NorthWind">
                    Update Employees
                    Set FirstName = '#Form.FirstName#',
                    LastName = '#Form.LastName#'
                    Where EmployeeId = #Form.EmployeeId#
                </cfquery>
            </cftransaction>
            </cflock> 

<!---------------------------------------------------------------------------------------------------------------
If updated properly, return to the previous page, with "errorcode = a" which "Success!"
--------------------------------------------------------------------------------------------------------------->

            <cflocation url="DataSet.cfm?ErrorCode=a" addtoken="No">
            <cfcatch type=
"Any">
<!---------------------------------------------------------------------------------------------------------------
If there were exceptions to updates, return to previous page with "errorcode = b" which was "Error updating the dataset" message
--------------------------------------------------------------------------------------------------------------->

                <cflocation url="DataSet.cfm?ErrorCode=b" addtoken="No">
            </cfcatch>
        </cftry>
    </cfcase>

<!---------------------------------------------------------------------------------------------------------------
same is true for deletes !
--------------------------------------------------------------------------------------------------------------->
   
<cfcase value="Delete">
        <cftry>
            <cflock timeout=
"30" throwontimeout="No" type="EXCLUSIVE">
            <cftransaction>
                <cfquery name=
"DeleteRow" datasource="NorthWind">
                    Delete from Employees Where EmployeeId = #Form.EmployeeId#
                </cfquery>
            </cftransaction>
            </cflock> 
            <cflocation url=
"DataSet.cfm?ErrorCode=a" addtoken="No">
            <cfcatch type=
"Database">
                <cflocation url=
"DataSet.cfm?ErrorCode=c" addtoken="No">
            </cfcatch> 
        </cftry>
    </cfcase>

<!---------------------------------------------------------------------------------------------------------------
for any other types of goof-ups ..... always account for "other" contingency. 
--------------------------------------------------------------------------------------------------------------->

    <cfdefaultcase>
        <cflocation url=
"DataSet.cfm?ErrorCode=d" addtoken="No">
    </cfdefaultcase>
</cfswitch>

<!---------------------------------------------------------------------------------------------------------------
You are done !
--------------------------------------------------------------------------------------------------------------->

In any case, whether an update was successful or not, you will be thrown back to "DataSet.cfm" with the proper message.
If updated, the table will reflect changes, if not it will display error !!
<!---
If you try the delete statement on this particular database, be advised, your referential integrity will not allow deletes.
Take off the cftry catch statements to see the following error !

Error Executing Database Query. 
[Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][ODBC SQL Server Driver][SQL Server]DELETE statement conflicted with COLUMN REFERENCE constraint 'FK_Orders_Employees'. The conflict occurred in database 'Northwind', table 'Orders', column 'EmployeeID'. 
---> 

Hope you find this easy and useful !!



All ColdFusion Tutorials By Author: Anang A Phatak
  • A DataSet just like VB.Net
    This tutorial shows you how to create a "dataset" just like the one in VB.Net In VB.Net you would create a dataset with "edit" button in an extra column. Once you click "edit", you get an option to "update", "delete" or "cancel edit mode" This is just like a cfgrid tag. Although a cfgrid tag lets you bulk insert, bulk update or bulk delete, the dataset object does it one by one. But cfgrid is slower, and may give users Java errors, depending on their browser settings.
    Author: Anang A Phatak
    Views: 16,140
    Posted Date: Wednesday, November 17, 2004
  • A Mp3 Streaming Server
    This is a small application that shows you how to create an MP3 streaming server.
    Author: Anang A Phatak
    Views: 13,341
    Posted Date: Monday, November 8, 2004
  • A plot to plot a line
    I had no work one day due to a worm attack on our servers, thus a plot to plot a line on a graph was hatched in my empty mind. These files show you, how to plot a line using no database, no java, no long wait times for aplet loading, just 3 tools, Loop, table and text.
    Author: Anang A Phatak
    Views: 8,997
    Posted Date: Thursday, May 6, 2004
  • A random password generator
    RANDOM PASSWORD GENERATOR SCRIPT ! I know there is a random password tutorial here already. This is just another way to do the same. I think this is a little easier to understand. Refresh it to generate a new password string everytime !
    Author: Anang A Phatak
    Views: 10,576
    Posted Date: Monday, May 24, 2004
  • Advanced Calculator
    I have posted a "Basic Calculator" tutorial here. That was more like a representation of how you would calculate with a paper and a pencil. You provide INPUT A then a MATHEMATICAL OPERATION like a "+" or a "-" and then an INPUT B. This is more a represntation of how you would use a regular hand-held calculator complete with buttons for NUMBERS, OPERATIONS and CLEAR TEXT.
    Author: Anang A Phatak
    Views: 9,557
    Posted Date: Friday, June 18, 2004
  • Automatic Form Generator
    This is not a tutorial as such, more like an application that you can put in a directory. It could boring if you use the CF editor, to pick "cfform" fill its attributes, then pick "cfinputs" one by one. fill out those attributes... one by one, then change tabs and pick the "submit" button... so on and so forth. Even if you code in a note pad, it might get lengthy to code individual element. Wouldn't it be nicer to code all these elements at once, then just copy the code and paste it in your editor?
    Author: Anang A Phatak
    Views: 10,157
    Posted Date: Thursday, May 20, 2004
  • Automatically Query To CFM
    This is a custom tag application. The cf_QueryRender custom tag takes your query arguments and gives you a final page table and all...
    Author: Anang A Phatak
    Views: 12,089
    Posted Date: Friday, October 29, 2004
  • Breaking down your query results into pages (Paging Tutorial)
    I havent come across a "paging" tutorial on this site. I know there are JavaScripts available that help you achieve this, and the DataSet object in VB.Net comes with paging. All you do is "enable paging". But how do you do it in ColdFusion ?
    Author: Anang A Phatak
    Views: 16,059
    Posted Date: Tuesday, November 16, 2004
  • Breaking down your query results into pages (Paging Tutorial) Part-II
    This is an extension to my last tutorial "Breaking down your query results into pages (Paging Tutorial)" which is posted here on www.easycfm.com In the last tutorial, you could retrieve a dataset with a , then use a technique to seperate the results over several pages. It simply ; - took the total "recordCount" - divided that with the "number of records per page" - then displayed the number of pages at the bottom of the table. This is a little more sophisticated than that. Read on...
    Author: Anang A Phatak
    Views: 8,489
    Posted Date: Wednesday, January 11, 2006
  • ColdFusion MX 6.1 Installation on Linux (Ubuntu -- Hoary Hedgehog)
    I have tried hoards of websites on how to install coldfusion on Fedora Core 3 with apache webserver. For some reason the connectors always failed. I had "Ubuntu" on my laptop, basically because "acpi" suspend/hibernate actually works. I decided I might try to install CF there to find out what was going wrong. Surprisingly everything worked like a charm. Make sure you use "apt-get install apache2" before you try this. BEST OF LUCK ....
    Author: Anang A Phatak
    Views: 10,906
    Posted Date: Tuesday, May 10, 2005
  • Dynamic textbox and progress bar for your pages
    The principle of this tutorial is similar to "Dynamic time and date for your pages" tutorial. Except that this one generates messages, and that one updated time. Read on, you will get the hang of it....
    Author: Anang A Phatak
    Views: 12,778
    Posted Date: Thursday, May 19, 2005
  • Dynamic time and date for your pages
    Have you seen the "www.EasyCFM" page closely? On the main page, top right, there is a place for time, and top left a place for day-date. Ever wonder how Pablo does it ? This is not a ColdFusion tutorial. Its JavaScript.
    Author: Anang A Phatak
    Views: 10,437
    Posted Date: Wednesday, January 5, 2005
  • Getting ColdFusion Studio for Linux
    I like using HomeSite+ for windows, and I am getting used to Dreamweaver Mx. But I still need something just as good for Linux. For some reason, I couldnt get "wine and Dreamweaver Mx" to work. So I "Googled" a bit and stumbled upon Eclipse and cfEclipse. Here is how to set it up.
    Author: Anang A Phatak
    Views: 11,467
    Posted Date: Wednesday, May 25, 2005