Cool Code at Lunch Webinar – Flex & Salesforce

I was the guest speaker on our "Cool Code at Lunch" webinar yesterday where I showed the basics of developing, upload and running a Flex application on Salesforce with the Force.com Toolkit for Adobe AIR and Flex. The example app was a simple DataGrid populated with Contacts.

CoolCode-Flex

The application turned out to be a really good starting point for most Flex applications so I thought I'd post it and see if it helps anyone out. I has methods for querying, creating and deleting data.

You'll need to download the Force.com Toolkit for Adobe AIR and Flex toolkit here to run this example.

Flex Application - main.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="600" height="300"
  backgroundGradientAlphas="[1.0, 1.0]" backgroundGradientColors="[#FFFFFF, #FFFFFF]" creationComplete="init()">

 <mx:Script>
  <![CDATA[

  import mx.collections.ArrayCollection;
  import mx.controls.Alert;
  import com.salesforce.*;
  import com.salesforce.objects.*;
  import com.salesforce.results.*;

  [Bindable] private var sfdc:Connection = new Connection();
  [Bindable] private var isLoggedIn:Boolean = false;
  [Bindable] private var contacts:ArrayCollection = new ArrayCollection();
  [Bindable] private var userId:String;

  private function init():void {
   login();
   if (Application.application.parameters.userId == null) {
     userId = "005600000000000";
   } else {
     userId = Application.application.parameters.userId;
   }
  }

  private function getContacts():void
  {

  sfdc.query("select id, name, email from contact",
   new AsyncResponder(
    function (qr:QueryResult):void {
    if (qr.size > 0) {
      for (var i:int=0;i<qr.size;i++) {

       // create a new object to hold the data
       var c:Contact = new Contact();
       c.email = qr.records[i].Email;
       c.id = qr.records[i].Id;
       c.name = qr.records[i].Name;

       // add the object to the array collection
       contacts.addItem(c);

      }
    }
    },sfdcFailure
    )
  );

  }

  private function createContact(c:Contact):void {

   // create an array to send to sfdc
   var aSo:Array = new Array();

   // create a new contact sObject to populate with data
   var so:SObject = new SObject("Contact");
   so.FirstName = c.first;
   so.LastName = c.last;
   so.Email = c.email;

   // add the sObject to the array
   aSo.push(so);

   sfdc.create(aSo,
    new AsyncResponder(
     function createResults(obj:Object):void {
      if (obj[0].success == false) {
       Alert.show(obj[0].errors[0].message.toString(),"Error creating new contact");
      } else {
       // do something like update the collection
      }
     }, sfdcFailure
    )
   );

  }

  public function updateContact(c:Contact):void {

   // create an array to send to sfdc
   var aSo:Array = new Array();

   // create a new contact sObject to populate with data
   var so:SObject = new SObject("Contact");
   so.Id = c.id;
   so.FirstName = c.first;
   so.LastName = c.last;
   so.Email = c.email;

   // add the sObject to the array
   aSo.push(so);

   sfdc.update(aSo,
    new AsyncResponder(
     function updateResults(obj:Object):void {
      if (obj[0].success == false) {
       mx.controls.Alert.show(obj[0].errors[0].message.toString(),"Error updating contact");
      } else {
       // do something like update the collection
      }
     }, sfdcFailure
    )
   );
  }

  private function login():void {

  var lr:LoginRequest = new LoginRequest();

  // hard code values for dev/local
  if (this.parameters.server_url == null) {

   //sfdc.protocol = "http";
   sfdc.serverUrl = "http://na5.salesforce.com/services/Soap/u/14.0";
   lr.username = "YOUR_USERNAME";
   lr.password = "YOUR_PASSWORD&YOUR_TOKEN";

  } else {

    lr.server_url = this.parameters.server_url;
    lr.session_id = this.parameters.session_id;
  }

  lr.callback = new AsyncResponder(loginSuccess, loginFault);
  sfdc.login(lr);

  }

  private function loginSuccess(result:Object):void {
  isLoggedIn = true;
  // start calling methods...
  getContacts();
  }

  private function loginFault(fault:Object):void {
  mx.controls.Alert.show("Could not log into SFDC: "+fault.fault.faultString,"Login Error");
  }

  private function sfdcFailure(fault:Object):void {
  Alert.show(fault.toString());
  }
  ]]>
 </mx:Script>

 <mx:DataGrid left="5" right="5" top="5" bottom="5" id="dg" dataProvider="{contacts}">
  <mx:columns>
   <mx:DataGridColumn headerText="Id" dataField="id"/>
   <mx:DataGridColumn headerText="Name" dataField="name"/>
   <mx:DataGridColumn headerText="Email" dataField="email"/>
  </mx:columns>
 </mx:DataGrid>

</mx:Application>

Contact Value Object - Contact.as

package
{
 public class Contact
 {
  public var id:String;
  public var first:String;
  public var last:String;
  public var name:String;
  public var email:String

 }
}

Visualforce page - MyPage.page

<apex:page>
  &lt;apex:flash src=&quot;{!$Resource.CoolCode}&quot;
  width=&quot;600&quot; height=&quot;300&quot;
  flashvars=&quot;userId={!$User.Id}&amp;session_id={!$Api.Session_ID}&amp;server_url={!$Api.Partner_Server_URL_130}&quot; /&gt;
</apex:page>