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
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
I think DevOps is now a rambunctious teenager - it's starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...