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

Creating Subforms

In the June issue of ColdFusion Developer's Journal (Vol. 1, issue 3), I hinted there might be a way to create subforms using inline frames. This article shows how - using a combination of inline frames, JavaScript, WDDX and, of course, CF.

Right now, inline frames are supported only by Internet Explorer, but because they're part of the official HTML specification it's hoped that the other main browser platforms will soon support them. Essentially, inline frames allow a developer to create a space on the screen that acts like a content island - a separate frame surrounded on all sides by the top frame. I'll show how this is done and the benefit of using inline frames instead of text areas to create a subform.

The other new technology used in this project, WDDX - the Web Dynamic Data Exchange - is an XML-based, Allaire-sponsored specification for transferring data over the Web between disparate programming environments. This project will use WDDX packets to transfer data between the JavaScript and ColdFusion environments as well as to transmit data from a form to an action template.

Listing 1 represents the code for the input form for this project: a stripped-down, Web-based Events List. The code for the input form itself is on Lines 85-98. The form is simple, consisting of only a few elements. Two text boxes appear for the client to fill in - one for Event Title, the other for Event Sponsor. This data, however, exists in a one-to-many relationship in the back-end database, e.g., a single event can have multiple sponsors. This is the central problem that a subform is designed to resolve - how to represent a one-to-many relationship in an elegant manner on an input screen (see Figure 1).

Other form elements include an inline frame, a submit button and a hidden field that will contain a WDDX packet to be shipped off to the action template when the form is submitted.

Lines 92-94 create an inline frame on the screen. This frame, named "displayinlineframe", will be used to display the name of each Event Sponsor as it's entered. Because this element is named, it's exposed to JavaScript (much like the form itself); its values and what's displayed in it can therefore be manipulated via scripting.

Manipulating the values of the various form elements via JavaScript is the foundation underlying this project. The form works this way: the client enters a title in the Event Title text box (see Figure 2), then enters a Sponsor in the Event Sponsor(s) text box and clicks the >> button. The onClick() event of the >> button fires a JavaScript function that takes the data from the Event Sponsor(s) text box, pushes it onto a JavaScript array, then dumps the contents of that array to a WDDX packet that's stored as the value of the hidden "wddxpacket" form element. It then clears the contents of the inline frame and also dumps the contents of the updated JavaScript array there so the client can see that the Sponsor was added. When it's all done, the client clicks Submit and the contents of the form - including the WDDX packet containing the data of the JavaScript array intact - are transmitted to the action template for processing.

Let's analyze the JavaScripting on this form line by line.

Lines 5 and 6 simply import the WDDX and wddxDes packages that are included in the beta 2 version of the WDDX Software Development Kit available from www.wddx.org. These JavaScript packages allow for the serialization (or creation) of WDDX packets as well as the deserialization of a WDDX packet into native JavaScript format. Line 10 creates an instance of the WddxSerializer object that will be used further on in the script.

Lines 12 and 13 create some global variables, one of which ("eventSponsorArray") is an array that will be used to hold the value for each Sponsor as it's added.

Line 15 is where the fun begins. Lines 15-35 constitute the addIt() function, which is called whenever the >> button on the main form is clicked. The first thing this function does is to see whether the client has filled in the Event Sponsor text box ("eventsponsortextbox"). If the client is attempting to submit an empty box, an error alert pops up and processing of the addIt() function is aborted. Otherwise, processing proceeds.

Line 23 pushes the value of "eventsponsortextbox" onto the JavaScript array, using the value of the "counter" variable as the array element index. Line 24 then increments the counter in preparation for future values.

Lines 26 and 27, respectively, clear the display in the "eventsponsortextbox" and the inline frame.

Line 29 calls the buildFinalDisplay() function, which builds an HTML table that contains an item in each table cell from the JavaScript array. It then writes this table to the inline frame for display to the client.

Line 31 serializes the JavaScript array into a WDDX packet and writes it to the value of the "wddxpacket" hidden form field.

Line 33 simply returns focus to the now empty "eventsponsortextbox" in preparation for input of the next Event Sponsor.

As items are entered into the Event Sponsor text box and submitted via the >> button, they're pushed onto a JavaScript array. A WDDX packet is secretly created and stored in a hidden form field containing this data, ready to be posted to the action template whenever the client clicks the form's Submit button.

A question that might arise: Why an inline frame? Why couldn't a regular text area be used for this project? In fact, a text area can be used for this project and works fine for what's outlined so far. But one thing that can't be done within the confines of a text area is to make its contents interactive - HTML and JavaScript coding within a text area will be rendered as straight text, not as an interactive Web document. But why is it important to be able to do that anyway?

Suppose the client entered an Event Sponsor and clicked the >> button. The client then noticed that there's either an error in his or her entry or the entry isn't really valid, i.e., it should either be updated or deleted altogether. Using a text area, there's no way to interact further with the data, and the client would be stuck with what was originally input. An inline frame, however, creates a space for a wholly separate HTML document to appear within the confines of its parent document. This is accomplished by writing a combination of HTML and JavaScript to wrap each element of the HTML table generated by the addIt() function; Line 41 of the addIt() function not only dumps the array element to an HTML table cell, it also wraps that element in a hypertext link that, when clicked, calls the deleteFromArray() function back on the parent document.

This function allows the client the opportunity to either update or delete a previously submitted item by setting the value of the "eventsponsortextbox" to the value of the element needing updating or deleting. It then moves the focus to that text box. This occurs on Lines 53-54.

Next, the item is deleted from the JavaScript array on Line 55. But because of the way JavaScript arrays function, only the value of the item is deleted from the array, not the array element itself, which remains intact with its original element index - only now its value is "undefined." This annoying feature must now be dealt with - we certainly don't want multitudes of undefined array elements cluttering up our data structures! One way to deal with the situation is to create an alternate, temporary array and push all undefined items in the original array onto it. The original array can then be reset and repopulated with clean data from the temporary array. This is done on Lines 56-65. Once done, the array can be dumped to the inline frame and to the hidden "wddxpacket" form field, just as it is in the addIt() function. By deleting, then resubmitting, items from the original array, the client can update or delete elements before posting the data to the action template.

Another feature of the JavaScripting on this form should be pointed out before we take a look at the action template. The body tag of the HTML document contains an onLoad() event handler, which calls the initialize() JavaScript function each time the page is loaded. This function checks whether a value has already been declared in the hidden "wddxpacket" field. This is done to solve a curious problem that crops up when, for instance, the client leaves the page and returns, which might occur if there's an error condition on the action template and the client returns to the form to resubmit. When the client leaves the form, all JavaScript variables -- including the central JavaScript array -- are deleted. However, the values of the form fields are cached. If the client returns to the form, it will appear that everything remained the same. The values in the inline frame were cached, so they'll remain intact, as will the contents of the "wddxpacket" field. But if the client then decides to add, update or delete anything, problems arise. The original JavaScript array was flushed when the client left the page, so what appears on the screen in no way reflects the contents of this crucial data structure (which at this point is empty). The initialize() function remedies the situation by first checking for the existence of the WDDX packet cached in the "wddxpacket" form field. If it finds this packet, it deserializes it into a native JavaScript array, restoring what was flushed when the client left the page. Everything is back to normal - problem solved.

Once the client completes the form and the Event Title and "wddxpacket" form fields are properly populated, the form is submitted to the action template for processing. Listing 2 represents the code for this action template.

The first thing the action template does is wrap all interactions with the database in <CFTRANSACTION> tags to preserve data and referential integrity. It then (Lines 9-12) inserts the contents of the "eventtitle" form field into the Events table. Remember, each singular event can have multiple Event Sponsors, so the next thing to do is to determine the key of the event just entered into the Events table. It'll be used as the foreign key for each record subsequently entered into the Sponsor table (Lines 14-17).

Lines 19-23 extract the data from the "wddxpacket" form field and deserialize them into a native ColdFusion array. This is the beauty of WDDX - it enables the developer to transmit complex data structures from one programming platform to another. In this case we translated a JavaScript array on the previous form into a WDDX packet, transferred that packet to the action template, then deserialized it into a ColdFusion array. Pretty nifty!

Once the ColdFusion array, populated by multiple Event Sponsors, is properly in place, it can be looped through. It inserts each element into the Sponsors table using the Event ID as the foreign key linking back to the Events table. Figure 3 illustrates the state of the Events table once this is accomplished; likewise, Figure 4 represents the state of the Sponsor table. Notice the mapping of the foreign keys from the Sponsor table back to their corresponding records in the Events table.

Once that's done, the <CFTRANSACTION> tag is closed and the process is complete.

Why create subforms this way? Why use JavaScript and WDDX to do this when, as detailed in CFDJ's June issue, a developer can create subforms using the <CFGRID> tag? Although not illustrated in this article, the technique outlined above allows the developer to control the client's domain of choices by using a data-driven SELECT box instead of a free-form text box for data input. This isn't possible using the <CFGRID> tag (but would be a welcome addition!). It also, in many ways, is a more intuitive way to arrange information on the screen and thus is easier to use from the client perspective.

By using a combination of ColdFusion, JavaScript, inline frames and Allaire's WDDX format for transferring data, the developer can create a subform that's screen-efficient and elegant to use. And because all processing is done client-side, subforms are generated and rendered exceedingly fast. This, at least, is an instance where pushing application code out to the client for processing makes for a more efficient and effective browsing experience.

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
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...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
No hype cycles or predictions of a gazillion things here. IoT is here. 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, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
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 ...
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 ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis 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. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote 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. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani 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. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
SYS-CON Events announced today that Nirmata 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. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...