Tutorial: Creating Flex Salesforce Mashups

The Apex Flex Library makes it embarrassingly easy to create Flex applications that interact with the Force.com API. This tutorial demonstrates the basics of how to start creating Adobe Flex and Salesforce mashups. By the end of the tutorial you will know how to create a simple Flex application and embed this within your Salesforce application. If you prefer watching a demonstration to reading text, skip to the screencast that demonstrates the process in about 15 minutes.

Introduction

This tutorial demonstrates how to create a simple Flex application that makes calls to the Force.com API. The Flex application is then embedded within a Force.com application as a Custom S-Control displayed on a Custom Tab.

As Adobe describes it, Adobe Flex is a 'rich Internet application framework based on Adobe Flash that will enable you to productively create beautiful, scalable applications that can reach virtually anyone on any platform.' The richness of the applications and the ease with which you can create them make Flex an ideal framework for extending your Force.com Platform.

The Apex Flex Library lets you effortlessly access the Force.com Web services API from within a Flex application. This native ActionScript library allows you to create connections and manipulate the API, much as you can do from the Ajax Toolkit.

The result of combining Flex and the Flex Library is a powerful way of easily extending the Force.com Platform. This can be done by simply using Flex to create beautiful interfaces to your data, perhaps creating or your own dashboards for example, or by using Flex to create more powerful Mashups: The What and Why - for example having the Flex application access your Salesforce data and other external APIs to produce something new.

What You Need To Get Started

Besides your DFC login, all you need is:

Flex Builder is Adobe's IDE for building Flex applications. It provides an integrated development environment, allowing you create your applications either by writing source code, or by dragging and dropping components from a palette--or some combination of both.

Instead of using Flex Builder, you can use the command-line Flex SDK to compile the application, and write your applications using your favorite editor instead!

The Apex Flex Library is where all the magic happens. This library makes interfacing with the Force.com API quite painless, as you shall see later. The library is distributed by Salesforce.

Getting It Done

Here's how you can build your own Flex applications and embed them into Salesforce. The first thing to do is unpack the Apex Flex Library to a directory somewhere. It comes with the pre-built Flex library as3Salesforce.swc that you will reference later. Figure 1 provides a directory listing, though this changes in later distributions where the library can be found in a bin directory. Be sure to check out salesforce.mxml, which is the source code for an awesome demo Flex application that makes use of all the functionality in the library. See Figure 8 for a screenshot of the demo.

Image:x_flex-sdk.gif
Figure 1: Directory listing of the Apex Flex Library

If you're using the IDE, start Adobe Flex Builder and create a new Flex project. If you're familiar with Eclipse you'll be right at home in this IDE. To create a new project select File->New->Flex Project. Figure 2 shows the result.


Figure 2: Creating a new Flex Project

Now you just need to make sure that your Flex project has access to the Apex Flex Library, that as3Salesforce.swc file. To do this, click on the Library path tab and Add SWC Folder. Then simply select the folder containing the expanded Apex Flex Library as shown in Figure 3.

Image:x_ide-project_library.gif
Figure 3: Adding the directory containing the Apex Flex Library

At this point you can begin coding by simply dragging and dropping components onto the canvas. To get a feel of what you can do with Flex, check out the Flex Demo Apps applications on Adobe's site. You'll find everything from canvasses and buttons to dynamic pie charts and graphs.

For the purposes of this tutorial, simply drag across a DataGrid component. Assign it a width and height of 100% and position it at 0,0.

Image:x_designview.gif
Figure 4: Design view with a DataGrid component

If you click on the Source tab you'll uncover the Flex MXML source code that was generated for you by this action. Delete one of the DataGridColumn elements and rename the other two to Id and Name. Flick back to the Design view and you'll see that your changes are reflected there too. Figure 5 shows the result.

Image:x_ide-step1.gif
Figure 5: Source view with basic DataGrid

Now let's start coding! The first thing to do is add a Connection object. This will make an object available that we can use to communicate with the Salesforce API. Do this by adding the following line:

<salesforce:Connection id="apex" />

You can do this in the IDE by typing <Con and hitting complete (control-space). Doing it this way will also make sure that the salesforce namespace entry is added to the Application element.

Now add an applicationComplete="login();" attribute to the top Application element. This tells the Flex application to call the login() method after the application has loaded. Finally, add an <mx:Script> element (again, hitting the IDE complete key will ensure all the extraneous stuff is taken care of) and create an empty function definition for login().

Image:x_ide-step2.gif
Figure 6: The simplest possible program

Figure 6 shows our progress so far. This is a complete program. It renders a data grid, and after the application starts calls the empty login() function. Oh, you'll want to identify the data grid so that you can reference it later in the code. In this case, we've added the attribute id="bg", essentially assigning it the name bg. The task now is to actually log in and fill the data grid with data.

First, logging in. This is implemented with a standard call to the apex.login() function, which you can simply duplicate in your own code. Here it is:


private function login():void {
  apex.login(  new LoginRequest({
        server_url : this.parameters.server_url,
        session_id : this.parameters.session_id,
        // put your own info here to test standalone
        username : 'myusername@mycompany.mycom',
        password : '123456',
        callback : new AsyncResponder(render)
        })
  );
}

This code is pretty straightforward, except for the callback which we'll get to in a minute. The session_id parameter is interesting. When a Flex application is embedded within a Salesforce application as an S-Control, the platform will automatically pass in the current session ID (via a merge field) and the Apex Flex Library will 'log on' using that information--no additional authentication information will be used. If, on the other hand, you want to run your Flex application stand alone, as a client on your desktop for example, then you'll need to fill in the username and password fields with your credentials.

Now, about that callback. You probably guessed that a lot of asynchronous handling is taking place. Essentially the applicationComplete="login();" attribute says: once this application has loaded, call the login() function. This happens asynchronously, at some point in the future of the application.

The login() code has something similar. The callback item essentially tells the apex.login() to call the render() function, asynchronously, at some point in the future once the application has logged in.

There's only one thing left to write, the render() function. Here's the code we used:


10. private function render(result:Object):void {
11.    apex.query("Select Id, Name From Account limit 30",
12.     new AsyncResponder(
13.     function (qr:QueryResult):void
14.           {
15.             var ar:ArrayCollection = new ArrayCollection();
16.             for (var j:int=0;j<qr.records.length;j++  ) {
17.                 ar.addItem( {Id:qr.records[j].Id, Name:qr.records[j].Name});
18.             }
19.             bg.columns = [new DataGridColumn('Id'), new DataGridColumn('Name')];
20.             bg.dataProvider = ar;
21.           },
22.         function (fault:Object):void {}
23.     ));
24. }

Let's go through the code:

  • Line 10 defines the function as taking a single parameter. This will actually represent the result of our apex.login() call, but we're going to ignore it completely.
  • Line 11 makes a simple Apex query. This belies the full power of the Apex Flex Library. You can make any Salesforce API call here using the apex object. In this case, we're doing a simple query over the Account object.
  • The apex.query call takes three parameters. First, the query itself, which we have on line 11. The second parameter is a callback (you should be getting used to these now!) to process the result of the query. This starts on line 13 and extends to line 21. The third parameter handles error conditions. This is defined on line 22.

It's not the only way to write this functionality, but it gives you a flavour of what it's like to write in ActionScript. The function defined on line 13 should be quite understandable. Line 15 creates a new ArrayCollection. Line 16 iterates through the results of the query, and adds items to the ArrayCollection--one for each record returned. Line 19 and 20 configure the data grid and establishes the ArrayCollection as a data provider for the data grid (recall that the data grid was given the identifier bg earlier).

That's it! The bin directory will now contain a Flex application, MyFirstFlexApplication.swf which you upload to the Force.com platform.

If you're using the command-line SDK instead of the IDE, use the following command to compile the application:

/flex_sdk_2/bin/mxmlc -compiler.include-libraries=/temp/FlexSalesforceXXX/as3Salesforce.swc salesforce.mxml

Just change the directory paths as appropriate.

Embedding the Flex Application

Now that you've built the bedrock of all your future amazing Flex/Salesforce mashups, all you need to embed it in your Salesforce application. The way to do that, is to use a Custom S-Control. You probably noticed the this.parameters.server_url line in the call to apex.login(). This is passed in as a merge field in the S-Control. By passing in the server URL and session ID like this, the Flex application has all it needs to actually log in. You can of course pass your own parameters in, in addition to these.

Here's a summary of the actions (you can also follow them in the screencast) to embed the Flex application that you just created.

  • Hit Setup->Build->Custom S-Controls->New Custom S-Control when logged into Salesforce.
  • Give it a Label and Name, say MyControl. It should be of type HTML S-Control
  • Under Filename, browse for the local MyFirstFlexApplication.swf file that you created earlier.

Finally, under Content, paste in the following HTML.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head></head>
<body scroll="no" >
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
   id="FlexSalesforce" width="100%" height="100%"
    codebase="https://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
<param name="movie" value="{!Scontrol.JavaArchive}" />
<param name="quality" value="high" /><param name="play" value="true" />
<param name="bgcolor" value="#f3f3ec" />
<param name="allowScriptAccess" value="always" />
<param name="flashvars"
   value="session_id={!API.Session_ID}&server_url={!API.Partner_Server_URL_90}" />
<embed src="{!Scontrol.JavaArchive}" play="true" bgcolor="#f3f3ec"
  width="100%" height="700" name="FlexSalesforce" align="middle"
  flashvars="session_id={!API.Session_ID}&server_url={!API.Partner_Server_URL_90}"
loop="false" allowScriptAccess="always" type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflashplayer">
</embed>
</object>
</body>
</html>

This is a standard template (hence instantly forgettable) that you don't really have to worry about. Notice the merge fields {!Scontrol.JavaArchive} and session_id={!API.Session_ID}&server_url={!API.Partner_Server_URL_90} that are automatically filled in by the Force.com platform.

Once you have your S-Control, you can surface it somewhere on your application. For example, you may want to embed it as part of the Account details page. We've chosen a simple route of just using a custom tab. To do this, hit Setup->Build->Custom Tabs->New Web Tab, give the tab a label (say MyTab) and choose Custom S-Control as the Tab Type. Finally, choose your S-Control, MyControl, as the S-Control to use, and hit Next a few times. This will create the tab, make it visible to all users and include it on all custom applications.

Figure 7 shows the result.


Figure 7: A Custom Tab displaying the result

How easy was that?

What's Next?

Now that you have this setup working, all you have left to do is apply some creativity in extending the Flex application to do something exciting, using the rich GUI features now available to you.

To get you started, check out the demo application that comes with the Apex Flex Library. The source is available in the salesforce.mxml file in the Apex Flex Library.


Figure 8: The Force.com Demo Application that comes with the Apex Flex Library

As Figure 8 shows, it's a comprehensive program that allows you to carry out a plethora of API calls. It also embeds a SOAP and debug log that let you track down errors.

Image:x_data_vis.gif
Figure 9: A rich GUI toolkit

As Figure 9 indicates, you now have a rich GUI toolkit at your disposal. Here are some ideas on taking this mashup further:

  • Embed dynamic graphs and charts, building your own enterprise dashboard.
  • Run the Flex applications stand-alone, on your browser instead of embedding them for a different experience--a rich web-side mashup,

Screencast Image:Key_icon.gif

Here's a 15 minute screencast Image:Key_icon.gif showing how to do all of this. You'll need to log-in to see it (if you're not already an DFC member, you can join DFC for free).

The screencast illustrates how to create a Flex application, code to the Apex Flex Library, and deploy the resulting Flex application as an S-Control. It uses slightly different code as it used an older version of the Apex Flex Library.

Summary

This tutorial shows how the Apex Flex Library makes it really easy to create rich Flex applications that interact with the Force.com Platform. The result is a new way to enhance your Force.com applications--you can create standalone application clients using Flex and the Apex Flex Library, which provide a rich user experience, or simply create Flex components that mashup your Force.com data and embed these in your Force.com application.

References