The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

Posts Tagged ‘force.com

Salesforce Analytics API Sample Code

with 6 comments

Spider ChartA picture is worth a thousand words, so goes the justification for graphic novels. I kid, I love the hell out of graphic novels but now I’ve been sidetracked and this is only the second sentence of this post.

So, the Analytics API. I’m pretty enamoured with it as it seems is Pat Patterson, and I think that it’s one of the most useful features the platform has ever made available. Presenting the right chart (or set of charts) to a manager or executive can empower them to make business decision in minutes, powerful stuff. To that end myself and a few of my fellow Tquilites have begun building an opensource library of Analytics API demos to aid you in aiding your clients/managers/execs.

Below I’ve included a few introductory steps to help you get started. To start with you’ll need the code from github.

Step 0

I’ll be stepping through the Google Charts Stacked Bar Chart example from github so you’ll be able to test this out yourself.

Step 1 – Create a report

Certain report formats map well to certain chart formats so make sure you choose the right type of report. For example, stacked bar charts map well to matrix reports, summary charts map well to pie charts.

Once you have created your report and have some interesting data, determine the report ID and keep it somewhere safe. Report IDs always start with “00O”.

Report ID

Step 2 – Create a Visualforce Page

As it says in the heading of this section, create a new VF page. Easy peasy lemon squeezy.

Step 3 – Include the chosen JS library

As with any web-based language you’ll need to include the JS library that you want to use. I’m going to use Google Charts in this example. Note I’m also using jQuery to make the AJAX callout.

 <script type=”text/javascript” src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script type="text/javascript" src="https://www.google.com/jsapi"></script>

Step 4 – Call the Analytics API

The API call can be made server-side or client-side, with this example making use of a client-side call.

    /** Fetch the JSON data representing the the report **/
    var jsonData = JSON.parse($.ajax({
        beforeSend: function(xhr) {
          xhr.setRequestHeader('Authorization', 'Bearer {!$Api.Session_ID}');
        },
        /** You'll need a URL parameter key called "id" that has a Summary Report id value **/
        url: "/services/data/v29.0/analytics/reports/{!$CurrentPage.parameters.id}",
        dataType:"json",
        async: false
        }).responseText);

The results of the callout are fed into the callback function and available through the variables “ai” and “ae” (see below).

Step 5 – Parse the resulting JSON & build the required data structure

The structure of the JSON depends on the report type but is fairly simple to understand. Be sure to use console.log() to investigate what’s going on if you get stuck.

    var chartData = new google.visualization.DataTable();

    chartData.addColumn('string', 'Stage');

    $.each(jsonData.groupingsDown.groupings, function(di, de) {
      chartData.addColumn('number', de.label);
    });

    $.each(jsonData.groupingsAcross.groupings, function(ai, ae) {
      var values = [];
      values.push(ae.label);

      $.each(jsonData.groupingsDown.groupings, function(di, de) {

        values.push(jsonData.factMap[de.key+"!"+ae.key].aggregates[0].value);
      });

      chartData.addRow(values);
    });

Step 6 – Generate the chart

Finally invoke the drawing of the chart along with any options required.

    var options = {
      title: jsonData.attributes.reportName,
      vAxis: {title: jsonData.reportMetadata.groupingsAcross[0].name},
      isStacked: true
    };

    var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
    chart.draw(chartData, options);

Voila! You now know the basics of building custom charts in Visualforce (or any other web language) using the Analytics API. To try this out log into your Org and then browse to:

http://[your salesforce instance]/apex/YourPage?id=[reportId]

Feel free to use this code anyway that you can imagine and we’d be over the moon if you contribute your own awesome to what we’re building. Fork us on github.

Written by Wes

November 10, 2013 at 4:57 pm

Salesforce JavaScript Remoting: Using Apex and JavaScript objects to pass data from client- to server-side and vice versa

with 13 comments

I’ve spoken about how to do this at a high-level during Cloudstock London and there are hints at how it can be done but no formal documentation that I’ve found, so here we are :)

Quite simply JavaScript Remoting will transform Apex objects and classes (or collections of these types) into JavaScript objects for you. The opposite is true too but there are some rules you need to observe.

Apex Types to JavaScript Equivalents

This is the easier of the type conversions in that you don’t have to really do anything to make it happen. The code below uses a custom class that I’ve defined but you can do the same with any sObject too. Let’s have a look at the code.

The Controller

public with sharing class RemotingObjectsController {

    /* The remoting method simply instantiates a two custom types, puts
       them into a list and then returns them. */
    @RemoteAction
    public static List<CustomClass> getClassInstances(){
        List<CustomClass> classes = new List<CustomClass>();

        CustomClass me = new CustomClass('Wes');
        CustomClass you = new CustomClass('Champ');

        classes.add(me);
        classes.add(you);

        return classes;
    }

    /* My custom type */
    public class CustomClass{
        public String firstName{get;set;}

        CustomClass(String firstName){
            this.firstName = firstName;
        }
    }
}

The Visualforce

<apex:page controller="RemotingObjectsController">
  <script>
      // Will hold our converted Apex data structures
      var classInstances;

      Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.RemotingObjectsController.getClassInstances}',
        function(result, event) {
          // Put the results into a var for pedantries sake
          classInstances = result;

          console.log(classInstances);

          // Assign the first element of the array to a local var
          var me = classInstances[0];

          // And now we can use the var in the "normal" JS way
          var myName = me.firstName;
          console.log(myName);
        });
  </script>
</apex:page>

The Output

Console output from the JS code.

JavaScript Types to Apex Equivalents

This is a little tricker, especially when it comes to sObjects. Note that the approach below works for classes and sObjects too.

The Visualforce Page

<apex:page controller="RemotingObjectsController">
  <script>
      /* Define a JavaScript Object that looks like an Account */
      /* If you were using custom objects the name must include the "__c" */
      function Account(){
          /* Note the field names are case-sensitive! */
          this.Id = null; /* set a value here if you need to update or delete */
          this.Name = null;
          this.Active__c = null; /* the field names must match the API names */
      }

      var acc1 = new Account();
      acc1.Name = 'Tquila';
      acc1.Active__c = 'Yes';

      var acc2 = new Account();
      acc2.Name = 'Apple';
      acc2.Active__c = 'Yes';

      var accounts = new Array(acc1, acc2);

      Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.RemotingObjectsController.insertAccounts}',
        accounts,
        function(result, event) {
          console.log(result);
        });
  </script>
</apex:page>

The Controller

There not much to the controller in this case.

public with sharing class RemotingObjectsController {

    @RemoteAction
    public static void insertAccounts(List<Account> accounts){
        insert accounts;
    }

}

Why is this cool?

Good question. If the Force.com Platform didn’t do this for you then we – the developer – would need to convert ours types explicitly on both the server-side and the client-side, and man-oh-man is that boring, error-prone work. Yet again the guys at salesforce.com have built in a convenience that saves us time and let’s us get on with the work of building cool apps.

Written by Wes

June 22, 2012 at 11:06 am

Salesforce: JavaScript Remoting – a different way of thinking

with 6 comments

 

Remoting is awesome.

JavaScript Remoting for Apex operates in a very different paradigm from what you might be used to i.e. Visualforce pages have controllers and the two interact through action methods – where this might be a full form submission or some neat AJAX functionality. Remoting also calls controller methods but there is a gaping maw in terms of how the two work under the hood.

I’ve seen a few great articles on the syntax and example usage of JavaScript Remoting for Apex but when I started using it I came across a number domain differences that weren’t documented anywhere. Hopefully my list here will help you in the learning process. The best way to describe the new way of thinking is to examine the features set in contrast to “normal” Apex and Visualforce.

How JavaScript Remoting Differs

  • Pass parameters naturally i.e. the call matches the method signature syntactically instead of requiring <apex:param/>.
  • Action methods when called in “normal” Visualforce can only return NULL or a PageReference. Remoting allows you to return a wider range of data types, even objects and collections.
  • Remoting methods have no access to the view state e.g. if a static variable is initialised to some value (outside the remoting method) a remoting method will see this as NULL unless it is re-initialised in that method! Conversely if a remoting method sets a state variable value the scope of that value is only within that method.
  • It’s much faster. I’m building an application at the moment that is 95% backed by JS Remoting and when I show it to other developers they are struck dumb for at least 3 hours because of the speed.
  • Neater debugging info in the browser console. Salesforce has done a great job of providing feedback directly to the browser’s console log.
  • Each method call gets its own executional/transactional context i.e. fresh governor limits per call!

If I’ve missed anything please let me know and I’ll add it. Viva la knowledge crowdsourcing!

Written by Wes

February 5, 2012 at 4:05 pm

Salesforce: Dynamically determining the field type of a dynamically determined sObject

with 2 comments

This solution is quite difficult to find.

Call me crazy but I need to do this from time to time, and every time I do I can’t remember how I did it before! So I then trudge through the API and the Apex docs until I find the answer and that’s no mean feat in this specific case. Well, no more my friends because I’m putting it right here on this very blog!

In short the code below will return (as a String) the type of field that we’re working with. Neither the name of the object or the name of the field need to be known in advance.

    public static String getFieldType(String fieldName){
    	// Assume that "sObjectName" is populated elsewhere
	Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName);

	Schema.DescribeSObjectResult r = t.getDescribe();
	Schema.DescribeFieldResult f = r.fields.getMap().get(fieldName).getDescribe();

	if (f.getType() == Schema.DisplayType.String){
		return 'String';
	} // .... else if

	return null;
    }

Written by Wes

February 1, 2012 at 9:33 pm

Salesforce: Different percentage unit test code coverage in different environments

with 3 comments

Spot the difference.

Many people are finding that their tests are reporting different degrees of test-coverage in different environments. There are a few things to check if you are getting inconsistent results but there’s a new bug in the wild. Before you assume you have the bug make sure that you’ve:

  1. ‘Run All Tests’ in each environment. This will tell you a few things viz.
    • Perhaps there are tests failing that are bringing coverage in that environment down.
    • There are some tests that only fail when run in the browser e.g. MIXED_DML_EXCEPTION will not rear it’s head through the IDE.
  2. Click the ‘Compile all classes’ link above the Setup > Develop > Apex Classes view. I’m not sure when this lil’ bugger first appeared but it’s darn useful. Essentially it makes sure that all the dependencies in your code are fulfilled e.g. if page A uses controller B that in turn refers to utility class C it’ll make sure each of those pieces exist and work (as far as compilation goes at least).
  3. Double-check your test classes to make sure they’re not data dependent. If they are and you have different types/amounts of data in your respective environments it’s 100% feasible that the test coverage will be different.

Now if you’ve checked all of the above you might have been afflicted by a new bug which, for some reason, counts braces, whitespace (and more!) as being uncovered by your tests. This is preposterous of course and to fix it simply remove all test history from the deranged environment. Re-running the test and/or deploying them should now be back to normal!

Written by Wes

November 30, 2011 at 11:01 pm

Salesforce: Stop email being sent on user creation or password reset or …

leave a comment »

I’ve had to do this a few times but infrequently enough for me to forget how to do it each time. Forgetting things isn’t usually an issue because of our Google Overlords and their mighty The Google but it’s quite a journey down the rabbit hole to find this specific information.

The reasons it’s tricky to find is because the setting that controls whether an email is sent to the user on creation is not directly associated with users but with DML. Long story short you need to set a particular Database.DMLOption e.g.


User u = new User();
// Add some details here ...

// Set the DML options
Database.DMLOptions dlo = new Database.DMLOptions();
dlo.EmailHeader.triggerUserEmail = false;

Database.insert(u,dlo);

Hopefully this information will now be easier to find next time I forget :)

Written by Wes

October 30, 2011 at 1:12 pm

Posted in Apex, SalesForce

Tagged with , , , , ,

Knowledge Tree for Salesforce User Roles

with 3 comments

UX that makes you say things like, "Gee Whizz" and "Cowabunga"

Many moons ago @ratherGeeky was searching for an AppExchange app that would neatly display user roles so that she could be the best admin she could be. I had a poke around and there were a few nice apps out there but nothing with a simple, neat display of user roles.

Since then CloudSpokes was created, and a competition to that effect was released using the concept and tools that I was going to use (@jeffdonthemic smells like turnips btw). The outcome of the competition was a few very cool apps, but nothing that was package-ready so I pressed ahead anyway.

I’m happy to announce that you can now get Knowledge Tree for Roles on the AppExchange for free. It’s definitely a point solution, very specific in the problem it’s trying to solve but I think it does that well. I have a roadmap for the product and will [ever so slowly] be releasing new features e.g. drag and drop will be killer.

If you install the app and like it then please, please, please (please (please)) review it as it helps exposure and will hopefully lead to me getting more time to work on it. If you don’t like it let me know why via email (wes@cloud-corporation.com) and I’ll do my best to turn your frown upside down.

Written by Wes

October 14, 2011 at 11:23 am

Follow

Get every new post delivered to your Inbox.

Join 2,198 other followers

%d bloggers like this: