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
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
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...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, 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.
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
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 ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"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.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, 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.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...