Thursday, May 5, 2011

Lazy loading tree with jQuery, Force.com, jsTree and REST JavaScript toolkit




I recently took part in my first CloudSpokes challenge and was lucky enough to be the winner. The challenge was to use the Salesforce REST JavaScript toolkit to create a tree component that represented the parent/child relationship of an object to itself (think parent account/account relationship). Another requirement was that it would load “lazily”, only loading one level of children at a time. This would allow for a quick overall page load if there was a deep and complex tree that needed to be rendered. Here is a link to the challenge.  

Below is an overview of my entry and my thought process. You can download the code in its entirety here.

What you will need

I decided to use jsTree to render my tree in. I had never used it before but it looked to have all the things I needed in order to render a fully functional tree. The documentation and files can be downloaded here:


I also had to download the REST JavaScript tool kit. This is a pretty slick toolkit created by Pat Patterson that makes using the REST API via JavaScript a breeze. You get the toolkit here:


Once I got both of these libraries I zipped them up and loaded them to my dev org as a static resource that I would reference later in my component.

Add all the files into a zip and load it to Salesforce

Lastly I created a custom object to run it on. This was a simple custom object named Parent Object with a lookup relationship to itself.

Parent Object 


Define lookup to itself
Now on to the code…


I decided to create my tree as a custom component so I would be able to use it across any object that has a relationship with itself. To learn more about custom components check out the Visualforce developer’s guide.


The first step was to define my custom component and all the attributes that would need to be passed to it to make it dynamic. We will see these referenced later in the code.




 

 

 

 
 


Next, we need to include the libraries from the static resource we uploaded earlier.




    

Then we define the div that the tree will be rendered in once the page loads.


Now we can get to the actual code that queries Salesforce and renders the parent/child tree. The following code is all written in JavaScript and I am leaving out the script tag in my demo because Blogger does not like it. The first thing I did was convert the attributes to JavaScript variables. This is not a necessary step. I just find it easier when I do not have to type the merge syntax around my variables throughout my code.


/////////////////////////////////////////////////
        //
        // VARS
        //
        //////////////////////////////////////////////////
         
      var objectToQuery = '{!objectToQuery}';
        var parentId = '{!parentId}';  
        var fieldToQuery = '{!childField}';
        var childRelationshipName = "{!childRelationshipName}";
        var parentRecordName = "{!parentRecordName}";

Since jsTree uses jQuery we need to get a reference to jQuery that works.  I also needed to load the jsTree themes and get an instance of the REST API Client.


//////////////////////////////////////////////////
        //
        // Get a reference to jQuery that we can work with
        //
        //////////////////////////////////////////////////
        
        $j = jQuery.noConflict();
        
        ///////////////////////////////////////
        //
        // Load the themes
        //
        ///////////////////////////////////////
        
        $j.jstree._themes = "{!URLFOR($Resource.restJavascript, '/rest/themes/')}";
        
        ///////////////////////////////////////
        //
        // Get an instance of the REST API client
        //
        ///////////////////////////////////////
        
     var client = new forcetk.Client('{!$Api.Session_ID}');

Next I created an instance of a tree and stick it in the “tree” div we created earlier.  You will see that three major things are defined here. (1) The plugins needed. (2) The parent node name, state and id. Notice that I use the id of the parent object as the id. I will reference that later as I build nodes for the tree. (3) The themes for the different nodes. These themes are what define what icons will show up for the different types of nodes and what type of children they can have.


//////////////////////////////////////////////////
        //
        // Instantiate the inital jsTree
        //
        /////////////////////////////////////////////////
        
        $j("#tree").jstree({ 
          "plugins" : [ "themes", "json_data", "ui", "crrm", "dnd",  "types" ],
        
             "json_data" : {
                 "data" : [
                     { 
                         "data" : parentRecordName,
                         "state": "closed", 
                         "attr" : { "id" : parentId }                     
                     },
                 ]
             },
             "types" : {
     "max_depth" : -2,
     "max_children" : -2,
     "type_attr" : "rel",
     "valid_children" : [ "default" ],
            
              ////////////////////////////////
              // Define the themes
              ////////////////////////////////
              
              "types" : {
    
       "children" : {
        "icon" : { 
         "image" : "{!URLFOR($Resource.restJavascript, '/rest/folder.jpg')}" 
        },
        "valid_children" : ["noChildren","children" ]
       },
       "noChildren" : {
        "icon" : { 
         "image" : "{!URLFOR($Resource.restJavascript, '/rest/leaf.jpg')}" 
        },
        "valid_children" : ["noChildren","children" ]
       },
       
       "default" : {
        "icon" : { 
         "image" : "{!URLFOR($Resource.restJavascript, '/rest/home.jpg')}" 
        },
        "valid_children" : [ "noChildren","children" ]
       }
     }
    } 
 });
         

The next two functions are the ones that query Salesforce for data. “firstNodeLoad” is called on page load and loads the children of the parent object. We will see this called later in my code. The second one called “loadNode” is used for every subsequent call and accepts an Id of a Salesforce object and queries for that object’s children.


//////////////////////////////////////////////////
    //
    // Load nodes
    //
    /////////////////////////////////////////////////    

 function firstNodeLoad() {
     
     var query = "SELECT Id," +fieldToQuery +", Name, (Select Id From "+childRelationshipName+") FROM " + objectToQuery + " WHERE " +fieldToQuery +" = '" + parentId + "'";
     client.query(query,parseNode);
     
    }
    
 function loadNode(parentIdPassed) {
    
     var query = "SELECT Id," +fieldToQuery +", Name, (Select Id From "+childRelationshipName+") FROM " + objectToQuery + " WHERE " +fieldToQuery +" = '" + parentIdPassed + "'";
      client.query(query,parseNode);
    
    }
    
    
Both of those functions call “parseNode” when their API call is complete and pass their results into it. This function parses the response and builds a node for each child found for that parent. It also determines if those children have children. 

//////////////////////////////////////////////////
    //
    // Parse the REST repsonse
    //
    /////////////////////////////////////////////////
    
    function parseNode(response) {
       
        for(var i=0; i < response.records.length; i++) {
         
         var hasChildren = false;
       
/// Determine if they have children
if(response.records[i][childRelationshipName]!= null) {
          
               hasChildren = true;
          }
   
   addNode(response.records[i][fieldToQuery],response.records[i].Name,response.records[i].Id,hasChildren);
  }
         
    } 
        
The final function “addNode” is called as each child is parsed in the parseNode function. This function takes all the information about that child and creates a node or “leaf” on the tree for the child. It defines things like style, id, closed, etc. You will notice that I use the record id for the id of the leaf. This way I will be able to quickly add children to it when I need to.
//////////////////////////////////////////////////
    //
    // Add each node
    //
    /////////////////////////////////////////////////   
    
    function addNode(localParentId,nodeName,nodeId,hasChildren) {
      
      ////////////////////////////////////////////
      //
      // Create a new node on the tree
      //
      ////////////////////////////////////////////
      
      if(hasChildren) {
   
    /// If it has children we load the node a little differently
    /// give it a different image, theme and make it clickable
    
    $j("#tree").jstree("create", $j("#"+localParentId), "inside",  { "data" : nodeName ,"state" : "closed","attr" : { "id" : nodeId,"rel":"children"}},null, true);

    
   } else {
   
    // Nodes with no trees cannot be opened and 
    // have a different image
      
       $j("#tree").jstree("create", $j("#"+localParentId), "inside",  { "data" : nodeName ,"state" : "leaf","attr" : { "id" : nodeId,"rel":"noChildren"}},null, true);
   
   }
   
 }
 
Lastly I need to bind some events to the nodes that are created in the tree.

The first event was to load any child nodes of a leaf if it was opened up by the user. This was a major requirement of the challenge. Up until now in our code we only query one level of the tree. I accomplished this by using the “open_node.jstree” method that is part of jsTree. Basically every time a node is opened I call the “loadNode” method on the children of that node and load up any children they may have.
//////////////////////////////////////////////////
    //
    // Add the logic to query if there are children
    //
    /////////////////////////////////////////////////
 
 $j("#tree").bind("open_node.jstree", function (e,data) {
  
  /// Make sure it is not the parent node 
  
  if(data.args[0].attr("id") != parentId) { 
  
   // Get the current node
           
           var thisNode = $j('#'+data.args[0].attr("id"));
          
           /// This makes sure that it does
           /// not load the childeren more than once
           
           if(thisNode.find('li').length == 0) {
           
            /// Load all the child nodes
            
             loadNode(data.args[0].attr("id"));
           
            }
  }   
    })
Then I also delegated the click of links (record names) within the tree to open up the record they represented in a new window.

//////////////////////////////////////////////////
    //
    // Setting up the link to the object on the label 
    // of a tree node
    //
    //////////////////////////////////////////////////

   $j("#tree").delegate("a","click", function (e) {
    
    /// Dont open a window for ultimate parent
    if($j(this).parent().attr("id") != parentId) {
    
     window.open("/" + $j(this).parent().attr("id"),"mywindow","status=1,toolbar=1,location=1,menubar=1,resizable=1,scrollbars=1");

    }
  });
 



Finally when it is all done I call the “firstNodeLoad” method to kick it all off.
////////////////////////////////////////////////
 //
 // Load the first node on window load
 //
 ////////////////////////////////////////////////
 
 window.onload = firstNodeLoad;


All I had to do now was include this component in a Visualforce page. You will see that we call the "lazyLoadingTree" component and then pass into it the attributes required to render the tree. This component could be called on any object that had a child/parent relationship with itself.



 









Then include that page in a standard page layout and I get this pretty little tree that loads “lazily”.




Hopefully this was helpful. It was my first time working with jsTree and I am a bit of a jQuery hack. As always would love to hear any feedback/suggestions. Thanks again to Pat Patterson for putting the toolkit together as well as CloudSpokes for putting on some fun challenges!



You can download the code in its entirety here.


Friday, April 29, 2011

Data three ways from Force.com…




Over the past couple of months there has been a lot of chatter about some new ways to access your Salesforce.com data. The REST API was released earlier this year as well as something called JavaScript remoting that is in developer release. I currently use standard Apex and Visualforce when creating custom apps on the platform so I thought I would take some time to better understand the REST API and JavaScript remoting.

I had a fun night playing with the code samples provided by Salesforce and thought I would share some examples. Below are three different ways you could access your data on the platform. My goal was very simple…query Salesforce for a list of accounts and display them in a table. Not earth shattering at all but hopefully the simple use case will illustrate three different approaches. Each approach will output a data table exactly like this:





Recipe 1: Using standard Visualforce page with Apex class

The first approach I took was to use an Apex class to query the data and then use a Visualforce page to display it. This is pretty standard Force.com development and should look familiar.

Here is the Apex class:
public with sharing class dataTableOne {

 public List getAccounts() {
  
  List accountsForPage = [Select Id,Name,Phone From Account Limit 10];
  return accountsForPage;
  
 }
}


Here is the Visualforce page:

 
Data retrieved using standard APEX/Visualforce
Account Name Account Id


Recipe 2: Using JavaScript Remoting

When I first saw Josh Birk (@joshbirk) demo JavaScript Remoting at the Minneapolis user group meeting my reaction was, “That looks a lot like those old s-controls we use to write before APEX/Visualforce”. After he talked me off the ledge I got a better understanding of what situations you might use remoting (mobile dev, no viewstate, etc). I used his blog post here to build my recipe below.

Here is the Apex class:
global class dataTableTwo {

    @RemoteAction
    global static Account[] findAccounts() {
       
        Account[] accountsForPage = [Select Id,Name,Phone From Account Limit 10];
        return accountsForPage;
    }


}

Here is the Visualforce page:


 
 
Data retrieved via JavaScript Remoting

Data retrieved via JavaScript Remoting


Recipe 3: Using the REST API and JavaScript toolkit

The last recipe uses the REST API to access the data from Salesforce and has no APEX class. I leaned heavily on Pat Patterson’s (@metaDaddy) blog post and the JavaScript toolkit he created. Thanks Pat! You can see below that once you include his toolkit as a static resource it is just a few lines of code to query data.


Here is the Visualforce page:


 
    
    
    
    
Data was retrieved via REST API

Hope this was helpful. Love to hear any questions or feedback.

Monday, April 18, 2011

The ABCs (I need x and y) of Force.com development…









A while ago I saw this blog post, “The ABCs of Web Development” by Siddharth. I enjoyed it so much I thought it might be fun to try to do the same thing with Force.com development. A draft has been sitting in Evernote for a couple weeks now and I only needed X and Y (XML seemed too easy) to complete. So I decided to put out my incomplete list and see if anyone had an X, Y or any other concepts/terms they might stick in here. I will update and give you credit if you send me one.

Below is what I have so far. I'd love to hear your thoughts or additions!


APEX - APEX is a programming language created by Salesforce.com that is hosted and run entirely on the Force.com platform. 

http://wiki.developerforce.com/index.php/An_Introduction_to_Apex

API - API stands for "Application Programming Interface". Think of it as a set of predefined methods you can call to interact with your Salesforce.com instance. 



Batch APEX - What you use to create large, complex, long-running jobs on the platform.


C

Custom Object - A custom object is pretty much the same thing as a database table. They can be defined through the declarative UI to extend your Salesforce data and have a number of field types you can add to them. 



DML - DML stands for "data manipulation language". This is basically all the different things you can do to modify your data in Salesforce (insert, update, delete, etc.).



Database.com (Submitted by @knhornt) - "Database.com is the world’s first enterprise database built for the cloud. It's open, proven and trusted. Database.com is built to power the next generation of Cloud 2 social and mobile enterprise apps." Definition from the Database.com website. This new Salesforce offering was announced at Dreamforce 2010.

http://www.database.com/


Data Loader (Submitted by @ashoknaglikar) - Desktop tool that allows you to easily access your Salesforce data.


http://wiki.developerforce.com/index.php/Apex_Data_Loader


Eclipse - Eclipse is an open source IDE in which you can develop your APEX and Visualforce code.


F

Flex - Flex is an open source framework for developing rich internet applications. Using Salesforce's APIs you can create very slick applications using Flex. There are a number of built-in UI libraries, as well as a powerful charting library that allows you to create powerful dashboards. 


Force.com Explorer (Submitted by @ashoknaglikar) - Direct from the developer.salesfore.com website: "The Force.com Explorer (beta) is a new cross-platform Force.com database explorer built with Adobe Flash Builder for Force.com. It's an AIR app, so you can get started pretty quickly: click here to install."
G

Governor Limits - Since you are developing in a shared environment Salesforce has implemented a number of limits to make sure your code is not taking up too many resources. If you reach a governor limit, your code will throw an error and stop running.


H

HTML - HTML stands for "Hypertext Markup Language" Ultimately all of your Visualforce code gets turned into HTML, so if you have an understanding of HTML you will be okay.



Heroku  (Submitted by @knhornt) - Heroku is a could based platform for developing Ruby applications. Salesforce announced that they would be buying Heroku at Dreamforce 2011.


 http://www.heroku.com/

I

IDE - IDE stands for Integrated Development Environment. The current IDE of choice for Force.com development is Eclipse. However, there a number of cloud based IDEs (BrainEngine) popping up that might give it a run for its money.


J

 jQuery - jQuery is an extremely fast and powerful JavaScript library that is commonly used by Force.com developers. It can be downloaded for free and uploaded to your Salesforce.com org as a Static Resource.


JSON (Submitted by @osamanasir) - JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language,


K

Keywords - A set of reserved words that you cannot use when naming variables, methods, or classes.


L

Log  (Debug Log) – “A debug log records database operations, system processes, and errors that occur when executing a transaction or while running unit tests. The system generates a debug log for a user every time that a user executes a transaction that is included in the filter criteria”.


M

MVC -  MVC stands for Model-view-controller. It is a software design pattern that is used in Force.com development. The idea is to separate the Model (Database or Custom Objects in SFDC) from the View (User interface or Visualforce in SFDC) from the Controller (Business Logic or APEX code in SFDC). 



N

nullPointerException - If you have ever done any APEX coding, you have probably run into this error. It is defined as "Any issue with dereferencing null".  It can be a frustrating little error that is sometimes hard to debug. You can find some examples of it in the APEX manual below.


O

Org - This term refers to a particular instance of Salesforce. 

P

Production - This refers to your "production" instance of Salesforce. All APEX coding must be done in a Sandbox or Developer instance and pushed to production once code coverage is reached.
Q

Query (SOQL and SOSL) - I know this is cheating a little bit since Salesforce's query languages actually start with S and not Q but I had a hard time finding a Q. Anyways, Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) are two ways that you can query Salesforce for data. SOQL has a syntax that is very similar to SQL and is primarily used to query Salesforce objects for a list of records that match a specific criteria. SOSL is used to search a list of lists of objects that contain a given search term.


R

Rerender attribute - Used in Visualforce to do partial page refreshes and create cool user interfaces. Used in this code sample:


S

standardController - This is the pre-built Visualforce controller that you reference if you create an Extension for a Visualforce page.  



Sandbox - (Submitted by @_siddhesh) - A sandbox is a replication of your production environment in which you do Force.com development before pushing to production. Below is a link that outlines the different types of Force.com environments.


http://wiki.developerforce.com/index.php/An_Introduction_to_Environments

Sites - (Submitted by @_siddhesh) Force.com sites allows you to create public facing web sites and applications that run on the Force.com platform and can leverage data in your Salesforce org.

http://developer.force.com/sites
http://wiki.developerforce.com/index.php/An_Introduction_to_Force.com_Sites

T

Trigger - Triggers are used to invoke APEX based on data changing in your Salesforce org. Triggers can be run on most objects when records are inserted, updated, deleted, merged, upserted and undeleted.


U

Unit Tests - "A unit test is code that exercises a specific portion of your codebase in a particular context." In order to get your code from a development or sandbox environment to a production environment you need to have 75% code coverage. This code coverage is gained by writing unit tests for your code. Basically, it is verifying that your code runs the way you think it should with no errors.


V

Visualforce - Allows you to create any user interface to run on the Force.com platform. 


W

Webservice methods - You can expose your own APEX class methods as a custom web service using the "webservice" keyword. This allows external applications to make calls to your APEX code within Salesforce.


X
Y

YouTube Salesforce Channel  (Submitted by @pbattison) - A collection of videos that are all about Salesforce.com. This site is maintained by @CRMFYI

ZIP archives - This is one of my favorite features of Force.com development. You can upload a zip file as a Static Resource with a bunch of images, JavaScript code, or whatever and then reference it on your Visualforce pages.

Sunday, March 13, 2011

Resources that helped me learn Force.com development





It has been five plus years now that I have been doing the majority of my development work on the Force.com platform. It has been a fun and sometimes frustrating journey to go from a self taught PHP developer who was at home with the LAMP stack to developing in the "cloud" with the Force.com platform. Since you can’t go to college to learn Salesforce's platform I thought I would take a minute to share with others the free resources that have helped me on many late nights as I hammered out some code for a client. This list is by no means exhaustive but it includes the main places I go when I need direction or when I need to sharpen my skills.

Salesforce.com generated content:

The first place I always turn to is the Salesforce.com generated content (most of which can be found at http://developer.force.com/). Hats off to the team at Salesforce for creating a killer platform and then taking the time to document it clearly. Weekly there are new webcasts about the platform and it seems like their documentation is updated with almost every release. If you are anything like me you don’t remember every bit of syntax...so I have the APEX, Visualforce, and API docs always bookmarked for quick reference.

They have also made available their "Dev 401 Building Applications" and "Dev 510 Apex and Visualforce" level classes on iTunes U so you can download over 15 hours of classroom teaching for free. If you are not familiar with iTunes U all you need is iTunes installed on your computer and you can download a bunch of very cool classes (Salesforce classes, Stanford iPhone dev classes, etc) for free. If you have the time these two courses are a great in-depth overview of development on the platform.

Lastly I will mention Dreamforce (even though it is not free… get your work to pay for it) the annual conference for Salesforce. There are tons of sessions you can attend to learn basic and advanced Force.com development. Plus you get to network, drink a lot of free beer and usually hear a good band.

The very active Force.com developer community:

From the developer evangelists to regular developers there are a number of very active and accessible people who are blogging, tweeting and making videos on how to work with the platform. Here is a short list of some of the blogs I have found most beneficial (I know there are many more out there...please email me if you know of some good ones!):

1. http://blog.sforce.com/ - This is the official blog that is maintained by Salesforce.com. A must-read to stay up-to-date on all things related to the platform.
2. http://gokubi.com/ - A blog written by Steve Andersen, a Solution Architect at the Salesforce.com foundation.
3. http://www.tehnrd.com/ - I love the style of writing on this one. Jason is also a great reference on how to use jQuery on the platform.
4. http://blog.jeffdouglas.com/ - Jeff is one of the co-authors of the Salesforce.com handbook and is always cranking out valuable content.
5. http://www.embracingthecloud.com/ - Written by Mike Leach at Facebook, this blog has in-depth entries on development on the platform.
6. http://wesnolte.com/ - The other co-author of the Salesforce.com handbook and a pretty smart chap.

I am a pretty late adopter to Twitter, joining only a couple of months ago. In that short time, a day has not gone by where I don’t learn about something new from the many people Tweeting about Salesforce. If you are not on Twitter join tomorrow and follow some of these people. Even if you don’t Tweet a thing, I guarantee you will learn a ton from the stream of consciousness out there. 

Two other areas to go for code samples are the Cookbook and the Code Share.

Force.com discussion boards:

In my opinion, the discussion boards on developer.force.com are the best place you can go to get accurate and quick advice when you are stuck on something. I have been on other boards where the tone of the experienced developers is arrogant and condescending. That is not that case with these boards. I remember when I was first starting out (and still today) asking pretty simple and basic questions with a little hesitation. Pretty much every time I have asked a question I have gotten a response from a fellow developer, evangelist or product manager that helps me figure out my issue. In the beginning this was the most important resource to me.

Developer challenges:

Over the past couple of years Salesforce has put on a number of developer challenges. These challenges have given me the freedom to be creative and create some stuff on the platform that no client would ever pay for. However, they have sharpened my skills and allowed me to think out of the box when it comes to the platform and what is possible on it. I regularly use code from my challenge entries when I deliver client work. I even have taken part in other companies challenges (PayPal) and written my entries on the Force.com platform. I would encourage everyone to take part in the challenges even if you have to work a couple nights to accomplish it. You learn a ton from them, meet fellow developers, and you might even win an Apple product. 

Banging my head against it:

Lastly, I am a self-taught guy. I do not have a Computer Science degree and have never taken a programming class. The only way I know how to get better at development is to do it, get frustrated, bang your head against some code for hours, and then finally figure it out. It is frustrating but when it clicks it is all good. Taking the time to get your hands dirty is probably the best way to learn the platform.

The Force.com platform is a great environment for a developer on these days and there is a mountain of resources out there to help you if you take the time to look for them. Hope this was of some value and would love to hear from you about all the resources I missed or simply don’t know about. Thanks!