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 a Component to Help You Collect Addresses

Squaring away address fields

Last month I introduced ColdFusion Components in this column. I wrote about the CFC file extension, the tags that make up components (cfcomponent and cffunction), how to create a component, and how to call methods on that component instance.

This month, I'll take you step-by-step through the process of creating a component that you can reuse in your own development. I'd be willing to bet that somewhere in your development adventures you've needed to collect an address from your users. Maybe you needed a billing address when you collected credit card information, or a shipping address when you sold a product through an e-commerce store. Perhaps you needed to collect a home address and a work address for the address book on your company's intranet. In this article, we'll create a standard component that you can use in all of these cases.

The Database Design
Before we can start writing code, we need to decide what type of data we want to store. A typical U.S.-based address will probably contain a street address, city, state, and zip. If you are dealing with international information, you may also want to store a country. Additional information might be a phone or fax number. You may want to store a name with your address information, although I usually have that information stored in a separate user table, so it's left out of this example (see Figure 1).

I added an AddressID field to the address table. This field is used as a primary key. When future tables or code reference an address they can do so using the primary key.

The street address is separated into two fields, Address1and Address2. This might be used in cases where the user needs one line for a street and house number, and a second line for an apartment number. State data is relegated to a separate table and referenced using a foreign key, StateID. I also added some date fields including DateCreated, TimeCreated, DateModified, and TimeModified. I add these fields to most tables, and will use them for reporting purposes.

Creating the Component
The first thing that we need to do is to set the instance variables of our component. I will set some initialization code in the pseudoconstructor area of the component. You may remember from last month that constructor code inside a component, but not inside a cffunction tag, is often called pseudoconstructor code. This code is executed every time an instance of the component is created (see Listing 1).

Integer fields, such as IDs, are initialized to zero. Text fields are initialized to empty strings. I initialized the date and time fields to empty strings, although in some cases I have initialized them to the current day or time. The instance data is placed in the variables scope, which means it is private to the component. All the instance data is placed in a structure inside the variables scope, which I called instance. This is so you can easily dump (using the cfdump tag) all the instance variables without having to display all the extraneous component information that would be displayed had you just dumped the variables scope.

The instance data is used to represent the database fields in the address table. It also contains the state data from the state table, such as state and state abbreviation. This data will probably be used primarily for display purposes in our application; when we update the address table, we'll only need the ID field.

You'll need a way to access the data from outside the component, since it is internal to the component. You can provide this through the use of getter and setter methods. A getter method is one that will get the value of a component variable. A setter method is one that will set the value of a component variable. Most of your getter and setter methods will be similar to each other, so I'll only give a simple example here. See Listing 2 for the get method for the address 1 variable

The name is GetAddress1, and the method is public. The return value is a string. The method body has a single line, which returns the value of the address1 instance variable. The set method is shown in Listing 3.

The name of this method is SetAddress1. Its access is public. The return type is a Boolean value. The method will return true if the set is a success, and false otherwise. Since this simple method does not contain any additional error checking, it will always return true (I'm making the assumption that the cfset will not fail).You could institute more complex error checking and have the method return false on failure. As an example, you may want to do this if a zip code has too few or too many characters. A single string argument is accepted for this method. The body consists of a cfset and a return.

Most of the get and set methods are simple, like the Address1 methods I just explained. One deviation is the StateID method. In reality, we could get by with just the StateID method, since that's the only field inside the address table. However, the state name and state abbreviation fields are included as a convenience to the developer. Listing 4 shows how the SetStateID method will retrieve this information.

This method accepts two arguments, the ID of the state and the name of the data source. It uses a query to retrieve the state data based on the ID passed into the function. Instead of just setting a single piece of data, it sets the state ID, the state name, and the state abbreviation. This method is an example of when more error checking might be beneficial. For instance, if nothing is returned from the query we could return false, or if the query failed for some reason we could return false.

Init and Commit Methods
A component's usefulness may be limited if it only has getter and setter methods. In our address component, we are going to add two additional methods. The first is an init method. The init method can be used to load data from the database and populate the instance data. The second method we are going to add is a commit method. The commit method will either create or update a database with the instance data of the component. Listing 5 shows the init method.

It accepts two arguments, the AddressID and the DSN. The AddressID is the primary key of the address record in the database. The DSN is the data source that refers to the database. It creates the name of the query as a local function variable using the var keyword. Then the code queries the database to retrieve the address information. The instance variables are set based on the query data and the function returns a Boolean true value.

The commit method is designed to update the information in the database. The code can be seen in Listing 6.

The method accepts the data source name (DSN) as the only argument. It checks the AddressID instance variable to see if we need to update the database or insert a new record. If the AddressID is 0, then we are dealing with new data. If the AddressID is not zero, then we can update that record in the database. If we create the new record, the AddressID is set. An SQL Server-specific method is used to retrieve the most up-to-date ID.

Using the Component
Now that you've created the component, how do you use it? Let's suppose you are creating a user component. The user component contains information about your users including their name, access levels, a home address, and a work address. How would I use the address component to create the home and work address? First, I'd initialize them in the constructor code using something like this:


<cfobject component="address" name="variables.instance.WorkAddress">
<cfobject component="address" name="variables.instance.HomeAddress">

I would add get and set methods, similar to Listing 7. For the set method, the address component initialization would be handled outside of the user method, and the component would be passed into the method as a variable. The argument type is the name of the address component, address.

To manipulate the address components through the user component you can use code like this:


UserComponentInstance.GetWorkAddress().GetAddress1()

Conclusion
This article should help you with the steps of building modular code. Components allow you to create the building blocks of an application. Over time, you'll develop a library of different components for different purposes, and then creating applications is just a matter of referencing your previously created jobs. As you start to develop a library of these components eventually your development will become quicker since you won't start every application from scratch.

More Stories By Jeffry Houser

Jeffry is a technical entrepreneur with over 10 years of making the web work for you. Lately Jeffry has been cooped up in his cave building the first in a line of easy to use interface components for Flex Developers at www.flextras.com . He has a Computer Science degree from the days before business met the Internet and owns DotComIt, an Adobe Solutions Partner specializing in Rich Internet Applications. Jeffry is an Adobe Community Expert and produces The Flex Show, a podcast that includes expert interviews and screencast tutorials. Jeffry is also co-manager of the Hartford CT Adobe User Group, author of three ColdFusion books and over 30 articles, and has spoken at various events all over the US. In his spare time he is a musician, old school adventure game aficionado, and recording engineer. He also owns a Wii. You can read his blog at www.jeffryhouser.com, check out his podcast at www.theflexshow.com or check out his company at www.dot-com-it.com.

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.


IoT & Smart Cities Stories
Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. 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 over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.