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
"We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, 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. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
"We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that EnterpriseTech has been named “Media 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. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
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 Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, 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. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and ...
SYS-CON Events announced today that CHEETAH Training & Innovation 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. CHEETAH Training & Innovation is a cloud consulting and IT training firm specializing in improving clients cloud strategies and infrastructures for medium to large companies.
SYS-CON Events announced today that Datanami has been named “Media 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. Datanami is a communication channel dedicated to providing insight, analysis and up-to-the-minute information about emerging trends and solutions in Big Data. The publication sheds light on all cutting-edge technologies including networking, storage and applications, and thei...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...