Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Creating Subforms with CFGRID

Creating Subforms with CFGRID

You're familiar with the rudiments of ColdFusion development. You know how to set and read local, session and client variables. You have input, updated and deleted data from a database. You've created drill-down "Master/Detail" templates by passing values in a URL string and you've created dynamic, data-driven SELECT boxes. Your forms look spiffy and everything is working fine, just like it did with Microsoft Access...well, almost.

Your Access application included an input form that contained a "subform" and allowed you to update two tables simultaneously. They were linked by a one-to-many relationship so for every record in your main table there could be a variable number of linked records in the secondary table. But you can't figure out how to accomplish this same layout and functionality within the restrictions of HTML. Luckily, the ColdFusion Markup Language contains a tag, CFGRID, that will enable you to do this.

The Scenario
Suppose, for instance, you want to create a Web-based "Experts List," i.e., a database of experts and lists of their respective topics of expertise. Each individual expert can have a variable number of these, so the database should therefore be designed with two tables - one containing the main record for the expert, the other containing a list of topics of expertise. These two tables should be linked in a one-to-many relationship, using the Expert ID as the key. Figure 1 illustrates the entity-relationship model of this simple database.

Input Form
The ColdFusion input form for this simple application will start out with some straightforward HTML tags. It will include TEXT boxes in which to input the expert's first and last names:

<form method="post" action="inputaction.cfm">
Firstname: <input type="text" name="firstname" size=25><br>
Lastname: <input type="text" name="lastname" size=25>

<input type="submit" value="Input It!">
</form>

Now it's time to program the subform for the variable number of topics, which is where CFGRID comes in.

HTML wasn't designed with databases in mind. Hence, there's no tag allowing for a subform structure. CFML was designed with data access in mind, and includes a Java applet - CFGRID - that adds a spreadsheetlike dynamic grid to your forms. This grid structure can be used as a subform within the confines of the regular forms we're all familiar with.

The first thing to do when adding a CFGRID to the form is to change the <form></form> tags. Because CFGRID provides complementary functionality to the regular HTML form tags, it must be surrounded by <cfform></cfform> tags. So the new form tags will look like:

<cfform action="inputaction.cfm">
.
</cfform>

Note that, by default, CFFORM uses the "post" method, so you don't explicitly need to state that within your tag.

The next tag is CFGRID, which allows a Web client to input a variable number of topics. The final input form, including the CFGRID code, can be seen in Listing 1.

The grid has an opening as well as a closing CFGRID tag. The opening tag sets attributes such as the grid name, width and height. It also sets a SELECTMODE - in this case "Edit" - that determines whether or not the Web client can interact with the data in the grid or just browse. The final attributes of the grid enable the Insert and Update buttons. It's via the Insert button that the Web client will be able to insert multiple records.

Within the CFGRID tags is a CFCOLUMN tag, which determines how many columns the grid will have as well as the format of the data in those columns. It also provides a name for the column - in this case "topic" - which will be used to insert data into the database via the final action template. Figure 2 illustrates how the form now looks.

To input data, fill in the Firstname and Lastname fields, then click on the Insert Topic button within the grid to insert each new topic, as illustrated in Figure 3.

For some reason you won't see the whole list of items you've entered within the grid until the length of your list of items approaches the height of the grid. When this happens, a scroll bar down the right side will pop up and allow you to see your entire list. This seems to be just a quirk of CFGRID. Once the input form is done, it's time to program the action template.

Input Action Template
Inserting the FORM.Firstname and FORM.Lastname fields into the Main table is pretty straightforward:

<cfquery datasource="experts"name="inputExperts">
INSERT INTO MAIN(Lastname, Firstname)
VALUES(#FORM.lastname#', #FORM.firstname#')
</cfquery>

Next, topics from the grid will be inserted into the Topics table via the CFGRIDUPDATE tag:

<cfgridupdate
datasource="experts"
tablename="Topics"
grid="insertGrid"
>

Now we have a few problems. First, if we try to run this action template, we'll get an error message because we've mapped a one-to-many relationship in our database design and enforced referential integrity between the Main table and the Topics table. When the CFGRIDUPDATE tag attempts to insert our topics into the Topics table, it does so with a default ExpertID of zero, breaking our referential integrity rule. So the first thing we must do is dive back into our database relationships and delete the relationship between the Main table and the Topics table. This doesn't mean that the relationship doesn't exist conceptually and logically - it just means that we're not going to have our database force referential integrity on us for the purposes of this application. (Don't worry, the logic of our application will ensure that referential integrity is preserved, as you'll see later.)

The second problem is that, because the new records in the Topics table are being inserted with ExpertIDs of zero, they don't map to the proper ExpertID in the Main table. First, you have to determine the ExpertID of the record we just inserted into the Main table, then update our newly inserted records in the Topics table so that the values in the two ExpertID fields correspond.

The following code determines the ExpertID for the record we just inserted into the Main table. It assigns that value to the "theID" variable:

<cfquery datasource="experts" name="getID">
SELECT MAX(ExpertID) AS theID
FROM MAIN
</cfquery>

Now that we know the value of the ExpertID field in the Main table, we can update the records in the Topics table that we just inserted so the value in their ExpertID fields correspond. This is done with a simple update statement:

<cfquery datasource="experts" name="setExpertID">
UPDATE TOPICS
SET
expertID = #getID.theID#
WHERE expertID = 0
</cfquery>

Now the ExpertIDs of our records in the Topics table match the ExpertIDs of the record in the Main table. And all is well with the world...almost.

Suppose that just before we determined the ExpertID from the Main table, someone else inserted another record. We might mistakenly think that the ExpertID that our records in the Topics table need is this new ExpertID, coming from a completely different record in the Main table. Likewise, suppose we've determined our true ExpertID from the Main table, but just before we go to update the ExpertIDs in the Topics table someone inserts several records. Our update would then include not only our records, but their records as well. In short, we need some way to ensure that all of the above code executes as a monolithic block and the database is "frozen" while we're interacting with it. Luckily, ColdFusion provides us with tags that provide just this sort of functionality. The final code can be found in Listing 2.

In summary, the action template (1) inserts a new record into the Main table, (2) inserts a variable number of topics into the Topics table, (3) determines the ExpertID of the newly inserted record in the Main table and (4) updates the ExpertID field of the newly inserted topics in the Topics table with this value. Because it does this all within CFTRANSACTION tags, the relationships and referential integrity of the database are preserved.

Figure 4 displays the contents of the Main table, while Figure 5 displays the contents of the Topics table after the Input Action template fires.

Update Form
The Update Form for this application will be similar in structure to the Input Form, but, like most update forms in CF, will be populated by queries from the database, as seen in Listing 3.

The getMainRecords query retrieves records from the Main table that match our criteria. In this case, the query is hard-coded and simply selects the record for Joe Schmoe, but your query will probably take its criteria from a set of FORM variables.

A CFLOOP is then opened that loops through the results of the getMainRecords query, building an update form for each record. Within each form there is an HTML input box of type "hidden" that will pass the ExpertID - the key - to the Update Action template.

Inside this main loop is another query, which grabs the topics from the Topics table based on the current value, from the getMainRecords query, of ExpertID. The getTopics query is then used to populate the grid.

Besides being populated by a query, another thing to note about the update grid is that instead of a single Topics column, it includes a hidden TopicID column. Just like a hidden field in an HTML form, a hidden field can be included within a CFGRID that will allow behind-the-scenes passing of a value. In this case we're passing along the TopicID value, a value that the Web client shouldn't have the opportunity to edit, but that is nevertheless crucial to the update function because it is the primary key of the topic record. Without this value the CFGRIDUPDATE in the Update Action template wouldn't know which topic to update.

Once the Update Form is populated, the Web client can insert, update or delete any of the topics in the grid.

Update Action Template
The Update Action template is actually much simpler than the Input Action template because the ExpertID has already been mapped between the Main and Topics tables. Thus, all that needs to be done is to update the Main table and let CFGRID do the updating to the Topics table, as seen in Listing 4. It's as simple as that.

Deleting Records
Deleting records from this application requires issuing SQL DELETE statements:

<cftransaction>

<cfquery datasource="experts">
DELETE FROM MAIN
WHERE ExpertID = 1
</cfquery>

<cfquery datasource="experts">
DELETE FROM TOPICS
WHERE ExpertID = 1
</cfquery>

</cftransaction>

These two queries delete all records from the Main and Topics tables that meet the specified criteria - in this case, that have ExpertIDs of 1. Your criteria will probably be taken from FORM variables, not hard-coded like the example above. (Also, using a more sophisticated SQL statement, you can delete records from more than one table simultaneously.)

Conclusion
If a simple gridlike structure will satisfy your layout and design needs, the CFGRID Java applet that ships with ColdFusion can be used to create easy-to-use and attractive subforms. When inline frames are supported in both of the main browser platforms, another more sophisticated technique for generating subforms may become prevalent, with ColdFusion and JavaScript code dynamically interacting with a CF action template inside the inline frame. But for now, CFGRID should do the trick for most simple subforms.

More Stories By Mark Cyzyk

Mark Cyzyk is the Web Architect at Johns Hopkins University in Baltimore,
Maryland.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
There is huge complexity in implementing a successful digital business that requires efficient on-premise and cloud back-end infrastructure, IT and Internet of Things (IoT) data, analytics, Machine Learning, Artificial Intelligence (AI) and Digital Applications. In the data center alone, there are physical and virtual infrastructures, multiple operating systems, multiple applications and new and emerging business and technological paradigms such as cloud computing and XaaS. And then there are pe...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...
In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...