Home  >  

Flex + Force.com: A Powerful Combination for Building Great, Data-Driven Web Applications

Author photo
AddThis Social Bookmark Button

Introduction

Flex and Force.com are a powerful combination for building data-driven web applications. As a faithful reader of InsideRIA, you’re probably already aware of Flex and its leading role in the evolution of rich Internet applications, but you may be less familiar with the Force.com platform. It is, in short, the same platform that underlies the well-known salesforce.com customer relationship management (CRM) and salesforce automation (SFA) software. These applications "run in the cloud," hosted on servers which are secured and maintained by salesforce.com, and accessed via the web on personal computers and mobile devices.

Force.com is analogous to Amazon Web Services (AWS) in that both the salesforce.com and Amazon corporations rent out the computing infrastructure on which they run their core businesses. However, while Amazon Web Services still requires you to do some of the software "heavy lifting" to get your application running, Force.com takes care of just about everything except the actual business logic that’s specific to your application, and which embodies the true value of your work. Typically, setting up a "serious" web application involves a lot of time and effort that contributes little value, but which is nonetheless a prerequisite to deploying the application. Building on Force.com, however, frees you from most of the distracting, time-sucking tasks so you can focus on the business logic and build a great application faster.

For example, with a few mouse clicks you can create custom relational database tables on the Force.com platform, and as soon as you finish configuring those tables, the Force.com platform also provides you a secure webservice for integration with other back-end systems (e.g. payment processing, inventory control), web forms for all the standard CRUD operations (create, read, update & delete), and web forms for searching the data. With a few more clicks, you can set up template email notifications, configure workflow and approval rules, or modify the default data access permissions. And, with all that, you also get instant scalability - your application can ramp up to tens of thousands of users at any time and without any intervention on your part.

Let me emphasize that the Force.com platform is not just for building sales- or CRM-related software; you can create just about any data-driven web application, and, thanks to Flex, the application can have any custom user interface. Force.com, especially with Flex on the front end, is a very attractive alternative to .net or PHP/MySQL, and, in fact, you may find that it’s often a great choice for even relatively-simple applications that would otherwise be developed with Microsoft Access and asp.net, for example.

There are several factors to consider when evaluating Flex and Force.com against the alternatives, most notably Force.com’s licensing fees. Salesforce.com’s pricing and edition hierarchy can be pretty confusing at first, so we’ll leave that to a subsequent article and instead focus on technical details. However, let me just say for now that there is a lot that you can do for free, including: learn to develop on the Force.com platform; develop full-featured prototype applications; develop and deploy one full-featured, non-CRM-related application; and develop applications to sell on the AppExchange, salesforce.com’s version of Apple’s iPhone AppStore.

In this article, we’ll learn how to create a custom Force.com database table, to publish data with a public XML web service, and to display the data in a browser-based Flex application. This is just the "tip of the iceberg" of the platform’s capabilities, but it’s a great place to start.

Let’s assume that we’re developing an application for a real estate agency. The application will enable the agency's employees to create, read, update and delete property listings, and to publish the listings via a simple web service that doesn’t require authentication, i.e. no user name and password are needed to view the data. With the Force.com platform, we can quickly accomplish this in four steps, and we’ll undertake a fifth step to create the Flex client that will display the listings in a sortable data grid.

The Force.com web administration interface can be confusing for the novice, and often requires some hunting through multiple layers of menus, pages and wizards. Therefore, if this is your first time using Force.com or Salesforce CRM (both of which share the same administration interface), you may find that this exercise requires a lot of hard-to-remember actions. But don’t be discouraged; once you have a little more experience with the Force.com platform, you'll be able to accomplish tasks similar to this exercise in minutes. Advanced developers and administrators can also use the Force.com IDE plug-in for Eclipse, which enables very quick coding and deployment on the platform. We’ll cover the IDE in a subsequent article, but if you’d like to try it in the meantime, it’s available for free here.

If you want to explore a fully-configured environment, you can login to the Force.com developer edition that I set up for this article. If you have two different browsers installed on your computer, use one browser to view the environment I set up, and the other to work through this exercise; that way the two Force.com sessions won't interfere with each other.

Step 1: Get a free Force.com developer edition environment

Go to this page and complete the form to get a free Force.com developer edition environment. Within a few moments, you’ll receive two email messages; one welcoming you as a new Force.com developer, and the second providing your temporary login credentials. Click the login link in that second message, or point your browser to https://login.salesforce.com and enter the user name and temporary password that you received. You’ll immediately be prompted to replace your temporary password with a new one of your choosing. Once you do that, you’ll be taken to the "Start Here" tab of your Force.com developer edition. You’ll see several sections with links to introductory material about developing on the Force.com platform, including "Learn the Fundamentals," "Build an Application," and "Participate in the Community." The latter section’s links will take you the Force.com online discussion forums and wikis, both of which are great resources for new and advanced developers alike.

By default, your user interface includes three tabs near the top of the screen, the first two labeled "Start Here" and "Home," and a third, smaller tab with a right-facing triangle. Clicking on the triangle takes you to a page where you can adjust the default settings so that other tabs are visible on-screen, including tabs for the well-known Salesforce CRM application like "Leads," "Contacts," "Accounts," and "Opportunities." We will not need those tabs for this exercise, but you can play around with them if you’d like to become more familiar with salesforce.com’s CRM and sales-related offerings.

Step 2: Create a custom Force.com object to store the property listing data

This is probably the longest step to describe in words because it involves so much clicking around the Force.com administration interface. I've added some screen shots to make the hunt for the right links easier.

Using Figure 1 as a guide, click Setup | Create | Objects | New Custom Object.

Click Setup | Create | Objects | New Custom Object
Figure 1: Click Setup | Create | Objects | New Custom Object

Enter the values listed in Table 1 below in order to define our new custom Listing object; for any form fields not listed in the table, simply accept the default value. Save the form when you are done.

Table 1: Defining the custom Listing object
  • Label: Listing
  • Plural Lable: Listings
  • Object Name: Listing
  • Description: A custom object to hold our real estate company’s current property listings
  • Record Name: Listing Number
  • Data Type: Auto Number
  • Data Format: LISTING-{0000}

You'll notice that some fields were created automatically with our custom object, including "Created By," "Last Modified By," etc., but there aren't yet any custom fields for storing information particular to the real estate listings.

Creating custom fields is easy with the Force.com web administrator interface. Click Setup | Create | Objects | Listing and press the "New" button in the "Custom Fields and Relationships" section. There is a four-step wizard for creating each new field; in the first step you'll select the field's data type, and in the second step you'll name the field and set some parameters for its possible values. In steps 3 and 4, just accept the default values that are already set; they're perfectly fine for this exercise.

Table 2 below displays the information you should enter in steps 1-2 of the four-step field creation wizard; for any form field not listed in Table 1, just accept the default value. If you want to view the fields that I have already created, you can see them here. (If you have two browsers installed, Firefox and Internet Explorer, for example, use one for following along with the steps in this article, and the other for viewing the environment that I already configured so that your Force.com sessions don't interfere with each other. If you use a single browser and get logged out, just login again at https://login.salesforce.com)

Table 2: Defining fields for the custom Listing object
Field Step 1: Select data type Step 2: Enter these values
(accept default values for fields not listed below)
Steps 3-4
1 Street Address Text Area
  • Field Label: Street Address
  • Field Name: Street_Address
  • Always require a value in this field in order to save a record: Checked
Accept defaults
2 City Text
  • Field Label: City
  • Field Name: City
  • Length: 255
Accept defaults
3 State/Province Text
  • Field Label: State/Province
  • Field Name: State
  • Length: 18
Accept defaults
4 Zip/Postal Code Text
  • Field Label: Zip/Postal Code
  • Field Name: Zip_Code
  • Length: 18
Accept defaults
5 Description Long Text
  • Field Label: Description
  • Field Name: Description
  • #Visible Lines: 3
  • Length: 32000
Accept defaults
6 Bedroom Count Number
  • Field Label: Number of Bedrooms
  • Field Name: Beds
  • Length: 4
  • Decimal Places: 0
Accept defaults
7 Bathroom Count Number
  • Field Label: Number of Bathrooms
  • Field Name: Baths
  • Length: 4
  • Decimal Places: 2
Accept defaults
8 Listing Type Picklist
  • Field Label: Type
  • List of possible values:
    • Single-Family Home
    • Townhouse
    • Apartment/Condo
    • Other
  • Field Name: Type
Accept defaults

The final part of this step is to add a tab to the Force.com administration interface. As I mentioned earlier, once you define your custom objects, you also automatically get customizable web pages and forms for querying, creating, updating, deleting and searching records. Those pages and forms are accessed via a custom tab, which is largely identical to the tabs that you already see on-screen.

Using Figure 2 as a guide, click Setup | Create | Tabs | New to create a new custom object tab for our Listing table.

Click Setup | Create | Objects | New Custom Object
Figure 2: Click Setup | Create | Tabs | New

Select "Listing" for the Object and then pick any tab style that you like. Leave the remaining, optional fields as-is and click "Next." Accept the default values for each of the ensuing pages and simply click "Next" at the bottom of each page. Finally, click "Save" when you arrive at the last page of the tab creation wizard. Your new "Listings" tab should be displayed at the top of your screen alongside the other tabs; if you don't see the new "Listings" tab, click on the little triangle in the right-most tab and you can manually add the Listings tab to your screen.

Click on the "Listings" tab and then press the "New" button to begin adding records to the custom Listing object. You'll notice that "Street Address" is a required field since we defined it as such earlier, and the Type drop-down list contains the values we provided when we defined the Type field. Create and save a few new sample Listing records.

Step 3: Develop a Visualforce page to format the data as XML

Visualforce is essentially the Force.com equivalent of Java server pages (JSP) or Microsoft active server pages (ASP) in that Visualforce enables the developer to merge retrieved data with static text in a web page template. Typically, the static text is HTML markup, but could also be XML, which we’ll use for our simple web service.

Using Figure 3 as a guide, click Setup | Develop | Pages | New.

new_vfpage.png
Figure 3: Click Setup | Develop | Pages | New

Enter "All Listings" and "AllListings" (no space) in the form fields for the label and name, respectively, of our new Visualforce page. Copy the code in Listing 1 below and paste it into the Visualforce markup area.

Listing 1: Visualforce page markup

 

<apex:page standardController="Listing__c" 
    recordSetVar="listings" 
    contentType="text/xml">
    
    <listings>        
        <apex:repeat value="{!listings}" var="listing">
            <listing>
                <street>{!listing.Street_Address__c}</street>
                <city>{!listing.City__c}</city>
                <state>{!listing.State__c}</state>
                <zip>{!listing.Zip_Code__c}</zip>
                <beds>{!listing.Beds__c}</beds>
                <baths>{!listing.Baths__c}</baths>
                <type>{!listing.Type__c}</type>
                <description><![CDATA[{!listing.Description__c}]]></description>
            </listing>
        </apex:repeat>
    </listings>
        
</apex:page>

The "standardController" attribute of the Visualforce page's apex:page tag tells the Force.com platform that the data will be drawn from our custom Listing table, created in step 2. The suffix "__c" (two underscores and the letter "c") is always appended by the platform to any custom table or field name, and must be included in any code that we write in Visualforce.

The "recordSetVar" attribute indicates that we want to work with a set of records from the object that was named in the "standardController" attribute, or in Force.com terms, we are using a list controller. The controller returns 25 records by default, and we could increase that amount by creating a list controller extension, though that is beyond the scope of this article; for now, 25 records are sufficient. The value of the "recordSetVar" attribute, "listings," is the name by which we'll refer to the record set in the ensuing Visualforce markup code; you could specify any other name that you like. The text inside the "apex:repeat" element will be rendered for each record in the "listings" variable, and each record will be referenced within the apex:repeat by the variable "listing."

Finally, note how we merged the data with the XML structure. The braces and exclamation point, as in "{!listing.Street_Address__c}," indicate that the enclosed text should be evaluated as a variable and replaced with the variable's current value. Force.com allows us to use dot notation to treat a database table row as an object reference, and to access its fields as we would an object’s properties, without having to write any query or database connection code.

Step 4: Create a Force.com Site to serve the data

The final Force.com-specific step is to create a public website that will serve the XML-formatted real estate listing data, and we’re going to use the newly-introduced Force.com "Sites" feature to accomplish this. Sites represent a significant enhancement to the platform, and makes Force.com an even more attractive choice for web application development. In the past, accessing Force.com or Salesforce CRM data required a username and password, i.e. a paid license. If you wanted to make the data available publicly and securely, that is, without handing out a username and password to anyone who might access your site, you would have had to develop and host a separate proxy application that would login to Force.com, query the data and then pass on the results to the Flex client. Now with Sites, however, you can easily and securely expose any subset of your data to clients without requiring a username or password (and without paying for a license for the client user).

To set up your Force.com Site, click again on the "Setup" link at the top of your Force.com web administration page. On the left side of the page, under "App Setup," click on "Develop" and then on "Sites." The next step is to choose your own Force.com "domain" name - I used "insideria" for this exercise and you can select any valid, unused domain name that you like. The domain name can never be changed and must be unique among all Force.com domain names, so don't use your company name or any other name you might use for a real Force.com application in the future. Read the terms of use and progress to the next step.

Enter the values listed in Table 3 below to configure the new Site; for any form fields not listed in the table, simply accept the default value. Save the form when you are done.

Table 3: Defining the Force.com Site
  • Site Label: Listing Service
  • Site Name: ListingService
  • Site Description: XML web service for serving real estate property listings
  • Site Contact: (Click the maginifying glass icon to locate your user name)
  • Active Site Home Page: (Click the magnifying glass icon to locate the Visualforce page "All Listings" - don't type the name manually...)

Once you've completed the Site configuration form, press "Save" and you’ll see a summary of your new Site's details (Figure 4). Press the button labeled "Public Access Settings," scroll down to the "Custom Object Permissions" section and make sure that "Read" is checked for the Properties object. If not, press "Edit," check "Read" and press "Save" at the bottom of the page.

Now we're ready to test our new, publicly-accessible, Force.com HTTP web service. Click on the link next to "Default Web Address" (see Figure 4) and you should see an XML-formatted page containing the sample property data you entered earlier. If you want to try the web service I set up for this article, go to the following URL: http://insideria-developer-edition.na7.force.com/ListingService

Click Setup | Create | Objects | New Custom Object
Figure 4: Site configuration

Step 5: Create a Flex application to display the data

Connecting a Flex application to our new Force.com web service is just like working with any other HTTP service that produces XML-formatted output. Below is the code for a Flex application, PropertyListings.mxml, that contains a sortable data grid for displaying the property listings data. Note that I'm using the URL of my service; if you need to find the URL of your service again, go to Setup | Develop | Sites and you’ll see it under "Site URL."

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
	layout="vertical" creationComplete="onCreationComplete(event)">
	
	<mx:Script>
		<![CDATA[
			import mx.utils.ObjectUtil;
			import mx.rpc.http.HTTPService;
			import mx.rpc.events.FaultEvent;
			import mx.rpc.events.ResultEvent;
			import mx.events.FlexEvent;
			
			private var _service:HTTPService;

			private function onCreationComplete(event:FlexEvent):void
			{
 				_service = new HTTPService();
 				_service.resultFormat = HTTPService.RESULT_FORMAT_E4X;
 				_service.addEventListener(ResultEvent.RESULT, onResult);
 				_service.addEventListener(FaultEvent.FAULT, onFault);
 				// The URL below is for my service - yours will 
 				// differ according to the Force.com sites 
 				// domain name you chose (mine is "insideria") and your
 				// Force.com "instance" (mine is na7, i.e. North America #7)
 				_service.url = 'http://insideria-developer-edition.na7.force.com/ListingService/AllListings';
 				_service.send();
 			}
		
			private function onResult(event:ResultEvent):void
			{
 				var xml:XML = event.result as XML;
 				myGrid.dataProvider = xml.listing;		
 			}
			
			private function onFault(event:FaultEvent):void
			{
 				trace(ObjectUtil.toString(event.fault));
 			}
		]]>
	</mx:Script>
	
	<mx:DataGrid id="myGrid" width="100%" height="100%">
		<mx:columns>
			<mx:DataGridColumn headerText="Street Address" dataField="street" />
			<mx:DataGridColumn headerText="City" dataField="city" />
			<mx:DataGridColumn headerText="State" dataField="state" />
			<mx:DataGridColumn headerText="Zip Code" dataField="zip" />
			<mx:DataGridColumn headerText="Baths" dataField="baths" />
			<mx:DataGridColumn headerText="Beds" dataField="beds" />
			<mx:DataGridColumn headerText="Description" dataField="description" />
		</mx:columns>
	</mx:DataGrid>
	
</mx:Application>
Let's briefly review some highlights of the Flex code. Notice that we set the result format of the HTTPService to "e4x," which means that Flex will parse the text returned from the Force.com web service, and automatically convert it to a Flex XML object. We also set the datagrid's dataProvider property to the the XMLList of "listing" elements, which are children of the XML root.

Conclusion

In this article we learned how to create a custom Force.com database table (object), a Visualforce page and a Force.com Site. We then created a publicly-accessible XML web service running on a Force.com Site, and connected that service to a Flex application with a sortable datagrid.

I hope this exercise gives you a taste of the power in combining Flex on the front end and Force.com on the back end. In subsequent articles we'll explore other aspects of the Force.com platform, and how you can use the platform to create, deploy and sell real-world, Flex applications.

Read more from Michael Epstein. Michael Epstein's Atom feed mike4aday on Twitter

Comments

16 Comments

Lead Management Solutions said:

Very nice and informative post on Flex + Force.com. I really had a
great time reading this post.. keep it up and looking forward to read
more soon.

Batsirai Chada said:

Fantastic - please do alot more Flex & Force stuff.

Some Force & Flex topics for RIA's
- app registration & subscription payment model using Force
- storage space & media on force.com using flex
- the use of appExchange plugins
etc

It does seem like a great combo - but there are needs for some intro tutorials to get people up and running - vs turning to mysql/php.

Keep going...

also see:
http://developer.force.com/flextoolkit

Romin Irani said:

Thanks for such a detailed article. The steps were clear and precise to follow. The Force platform looks good for a lot of things that I might have had to build from scratch.

Do you plan to cover things like adding/modify/deleting custom objects via the Web Services in your next installments?

Michael Epstein Author Profile Page said:

Romin,
Sorry for the delayed reply. Are you referring to creating custom objects via the metadata API? If so, that's a great idea, but more of an advanced topic and probably better suited to a later article, after some more fundamental topics. If you're interested in creating objects outside the standard web interface, you could also use the Force.com IDE plugin for Eclipse.
Thanks very much for the feedback

David said:

Michael great article. Thanks for the great info. I liked the fact that you took the time and prepared those screenshots as well!

Will be back for sure!
Skull tee

james lee said:

salesforce is so good to use. We use it at work and it is amazing. You really go into detail about it. I would love to hear more.
Orlando Personal Injury Lawyers

Bill Gable said:

Nice review, it will help many bloggers. As for me personally, I have already founf a step-by-step plan to blog the conference at http://developer.force.com/flextoolkit and like it very much! The advice is pretty clear and easy to follow.

Gawer said:

I think this is a wonderful idea to talk about it, and I am really grateful I found your website (Done by Software Downloads )

Michel White said:

This is one of the most useful Internet resources that I have seen. Thanks! ;)

business card scanner said:

Very well written article indeed, thank you so much for sharing such information with us, i hope we will see more from author in the future. Cheers. business card scanner

Mike said:

Michael great article. Thanks for the great info. I liked the fact that you took the time and prepared those screenshots as well! social security office locations

jthomps said:

Thank you so much for the great info. This is going to be really helpful for me!

-Andrew

Andrew Saladino said:

I'm a recent computer science graduate and I've never even heard of Force.com or Flex. After reading this tutorial, you sparked my interest and I'm definitely going to be reading a lot more tutorials on this platform. Thanks a lot
-Andrew

Jay Thompson said:

What they really need to ban are typos. Sorry about all of them in the comment above!

Mike said:

Like Andrew, I have also never heard of Force.com or Flex. It certainly looks very interesting and something that I will certainly look into more closely.
Mike

Leave a comment


Tag Cloud

iPad

What's your take on the iPad? (Putting aside the Flash/iPad flame war)

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.