The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

Archive for the ‘JavaScript’ Category

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

Voodoo – A Todo list that demos the power of KnockoutJS

with 6 comments

Voodoo - A todo list

This small demo app will demonstrate the usage and power of JavaScript MVC frameworks and in particular KnockoutJS. You can learn more about the framework through the tutorials on the KO site. I will gloss over some of the details but you can learn more in framework documentation. My goal here is to give you a high-level sense of what’s possible. The picture along side shows what we’re building. You can find the demo here and the full sourcecode here.

The HTML

Strictly speaking jQuery is not required for KO to work but it is likely that you will often include it as a helper for the framework. As alway you need to start with the static resource inclusions.

<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/knockout-2.0.0.js"></script> 

And you’ll need a form in order to create new todo items.

<form data-bind="submit: addTask" id="create-todo">
    <input class="new-todo" data-bind="value: newTaskText" placeholder="What needs to be done?" />
</form>

For the first time you’ll notice the data-bind attribute. The framework recognises this attribute and parses the attribute value to determine what logic to apply. In this case the input element is bound to a JavaScript property called newTaskText.
Next up you need the markup that contains and displays each task. Some actions are available for each item too.

<div class="todos">
  <ul data-bind="foreach: tasks, visible: tasks().length > 0" id="todo-list">
      <li>
        <div class="todo" data-bind="css: { editing: isEditing }, event: { dblclick: startEdit }">
          <div class="display" data-bind="css: { done: isDone }">
            <input type="checkbox" class="check" data-bind="checked: isDone" />
            <div class="todo-text" data-bind="text: title"></div>
            <a href="#" class="todo-destroy" data-bind="click: $parent.removeTask">&times;</a>
          </div>
          <div class="edit">
            <form data-bind="submit: updateTask">
              <input data-bind="value: title" />
            </form>
          </div>
        </div>
      </li> 
  </ul>
</div>

Again you’ll notice that each element that is to be used in someway by KO has an attribute of data-bind. Below I’ve picked out a few lines to demonstrate key functionality. The following line is an instruction to run through a collection of tasks and only display the ul element if there’s anything in the collection.

<ul data-bind="foreach: tasks, visible: tasks().length > 0" id="todo-list">

The line below is used to conditionally apply a style class and ensures that the doubleclick event is bound to the appropriate handler.

<div class="todo" data-bind="css: { editing: isEditing }, event: { dblclick: startEdit }">

And here we have an example of an input element being bound to a JavaScript object field isDone – the object structure will be shown later.

<input class="check" type="checkbox" data-bind="checked: isDone" />

Now here’s some of the magic of KO. Below are the some stats based on the number of tasks in the list. If you were using jQuery or just JavaScript you would have to track the number of elements in the list and update the stats appropriately.

You have <b data-bind="text: incompleteTasks().length">&nbsp;</b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> - its beer time!</span>

With KO the view is driven by the underlying object data. If the number of items in the list changes all related information is automatically updated in the view! In KO this is facilitated through concepts known as observables and dependency-tracking.

The JavaScript

KO is the first time I’ve used OOP within JavaScript for some time, and it’s pleasure to work with the concepts in such a paradigm! In this small app there are only 2 classes, one for tasks (fairly obvious) and another for the ViewModel which you can consider the application class.
The Task class contains the properties and methods applicable to Tasks. You’ll notice how the properties are initialised using using the ko.observable() method. This is a touch more magic and it means that the values of these properties will be “watched”. If they are changed either through the user interface or via JavaScript then all dependent views elements and JavaScript values will be changed too.

function Task(data) {
    this.title = ko.observable(data.title);
    this.isDone = ko.observable(data.isDone);
  this.isEditing = ko.observable(data.isEditing);

  this.startEdit = function (event) {
    this.isEditing(true);
  }

  this.updateTask = function (task) {
    this.isEditing(false);
  }
}

The ViewModel class exposes the Tasks in a meaningful way and provides methods on that data. Types of data exposed here are observable arrays of tasks and properties that return the number of complete and incomplete tasks. The operations are simple add and remove functions. Right at the end of the class I’ve used jQuery to load JSON objects into the todo list.

function TaskListViewModel() {
    // Data
  var self = this;
  self.tasks = ko.observableArray([]);
  self.newTaskText = ko.observable();
  self.incompleteTasks = ko.computed(function() {
    return ko.utils.arrayFilter(self.tasks(),
    function(task) {
      return !task.isDone() && !task._destroy;
    });
  });

  self.completeTasks = ko.computed(function(){
    return ko.utils.arrayFilter(self.tasks(),
      function(task) {
        return task.isDone() && !task._destroy;
      });
  });

  // Operations
  self.addTask = function() {
      self.tasks.push(new Task({ title: this.newTaskText(), isEditing: false }));
      self.newTaskText("");
  };
  self.removeTask = function(task) { self.tasks.destroy(task) };

  self.removeCompleted = function(){
    self.tasks.destroyAll(self.completeTasks());
  };

  /* Load the data */
  var mappedTasks = $.map(data, function(item){
    return new Task(item);
  });

  self.tasks(mappedTasks);
}

The very last line in the JavaScript code tells KO to apply all it’s magic using the ViewModel and markup we’ve written.

Summary

To me it’s amazing how little code you need to write in order to build such a neat app. And you don’t even need to track the view state at all! Hopefully this gives you the confidence to start using JavaScript MVC/MVVM frameworks because in the end it helps save you heaps of time and effort.

Written by Wes

March 23, 2012 at 5:58 pm

The rise of JavaScript and it’s impact on software architecture

with 4 comments

MVC and it’s siblings have been around for a while and developers are comfortable bathing in the warm light of their maturity and wide-spread advocation. However, a few years ago developers started doing more of their coding client-side and as a natural consequence the lines between M, V and C became blurred leaving many of us cold and uncomfortable when trying to explain where the architectural puzzle pieces belong.

I’m sure you’ve had a similar experience. Anyone who’s used jQuery, for example, has been in the uncomfortable situation where controller code now exists within view and even worse these two are tightly coupled by virtue of jQuery selectors. To make matters more complicated if you’ve ever used class-names for application state or .data() then you’re model, view and controller are now more tightly bound than the figures in a Kamasutra carving.

This is not a new problem but the solution(s) are quite new to me and so I thought I’d share my experiences.

jQuery is Great. But…

Read the rest of this entry »

Written by Wes

March 18, 2012 at 6:05 pm

jQuery Org Chart – a plugin for visualising data in a tree-like structure

with 187 comments

jQuery OrgChart is a plugin that allows you to render structures with nested elements in a easy-to-read tree structure. To build the tree all you need is to make a single line call to the plugin and supply the HTML element Id for a nested unordered list element that is representative of the data you’d like to display. Features include:

  • Very easy to use given a nested unordered list element.
  • Drag-and-drop reorganisation of elements.
  • Showing/hiding a particular branch of the tree by clicking on the respective node.
  • Nodes can contain any amount of HTML except <li> and <ul>.
  • Easy to style.

jQuery OrgChart


Expected Markup & Example Usage

All documentation can be found on github.


Demo

You can view a demo of this here.


Sourcecode

Source code with an example is available here.

Written by Wes

December 1, 2011 at 9:34 pm

Across the Pond with Shannon Hale

leave a comment »

Shannon is Senior Product Manager for Declarative Apps at Salesforce.com

@abhinavguptas and I were curious as to the identity of the creator of the SetupScripter, which is now incorporated into the salesforce.com Org setup menu. I dug around a bit and managed to uncover her real identity – community please meet Shannon Hale, Shannon Hale this is the community. She didn’t just stop with that wonderful piece of UX but has moved onto bigger and better things, but I’ll let her tell you about those.

If you’d like to learn more about the genius that is Shannon or just have a chat with her you can get her on twitter at @shannonsans or @bathtubdreamer. You can also check out her online presence at shannonsansserif.com and bathtubdreamer.com.

Onto the Q&A!

Who is Shannon Hale? How did you get into software development and UX design?

I started out as a writer, but in a different field — I wrote and edited for some independent Canadian music and culture magazines. I started technical writing to help pay the bills, and from there wandered through a series of tech positions: technical training, systems analysis and design, and software development. In 2001 I became obsessed with why a product I was coding was difficult to use, and began to independently study interaction design and user experience.

When I’m not being a complete geek — which I am even at home, I always have personal and volunteer web projects going on — I’m sewing, knitting, or binding books. I’m one of those people who always needs to be doing something with their hands.

Read the rest of this entry »

Written by Wes

October 14, 2011 at 10:49 am

Salesforce: A better way to work with jQuery selectors and Visualforce Component Ids

with 24 comments

Irregular Expressions

I get very sad when discussing this particular topic. There are a variety of ways of get Visualforce component Ids and using them in JavaScript but all of them keep me awake at night. Srsly. A commenter on one of my posts got me thinking about how we can do this better and I’ve come up with a way that I think is great. Hopefully you’ll agree.

This post means that my older posts here and here are now retired in favour of this method.

If the world was on the brink of nuclear war with no clear path to peace what could you count on to save the day? Regular Expressions of course. If a meteor the size of Pluto was about to crash into Earth and Bruce Willis was too old to land on it and blow it up what could we count on to rid us of the troublesome rock. Yes that’s right, Regular Expressions. I think you can guess where I’m going with this.

jQuery has the ability to understand very simple regular expressions in it’s attribute selectors. The full documentation can be found here.

To solve our particular problem however the code is simple:

<apex:page>
    <head>
        <style>
            a,span{
                display:block;
            }
        </style>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

        <script>
           jQuery(document).ready(function($){
               $('#btn').click(function(e){
                   e.preventDefault();

                   console.log('The following element was found when looking for an id of \'output1\':');
                   console.log($('[id$=output1]')); /* Here's where we're grabbing the element. */
               });
           });
        </script>

    </head>

  <apex:outputText value="She sells seashells by the seashore." id="output1"/>
  <apex:outputText value="Peter Piper picked a pack of pickled peppers." id="output2"/>

  <a href="" id="btn">Click me.</a>

</apex:page>

The important part here is the selector $(‘[id$=output1]’) which says, “Find the id value that ends with ‘output1′”. This comes with a warning though! Do not duplicate the Visualforce Id that you give to your elements otherwise this piece of code will find all of them.

When I first wrote this post I used a selector extension library that gives you the full power of JavaScript-based regular expression but Ryan Fritts has rightly shown that the above will deal with 99% of use cases and is simpler. For those of you that need to deal with the extra 1% I’ve implemented a wrapper to regex selector as an example. It does exactly what jQuery is doing above and gives you access to the regex flags as documented here.

Thanks again Ryan!

Written by Wes

June 24, 2011 at 2:36 pm

Across the Pond with Jason Venable aka TehNrd

with 5 comments

The face of TehNrd

Today I start a series of posts that’ll appear here and on the Tquila blog. The series will be in the format of Q&A with some of the finest Salesforce.com and Force.com evangelists, admins and developers. I’m starting with Jason Venable aka TehNrd and I’ll let him introduce himself.

Q: Tell me a bit about yourself. How long have you worked with the CRM vs the Force.com Platform? Were you always a developer?

A: My name is Jason Venable. I am 27 years old. I live in Seattle, Washington, USA. Oh, wait, you want something more interesting, got it. I’ve been working with salesforce.com CRM for a little over 4 years. Three of these years have also been working with force.com. All of this time has been administering and developing for a large enterprise salesforce.com deployment at F5 Networks. A lot of what I do is merging the two worlds of salesforce.com and force.com to meet business needs. This includes using all of the features force.com has to offer including, custom objects, validation rules, Apex code triggers, Visualforce pages, and web services to enhance and improve our companies use of salesforce.com.

Have I always been a developer? Heck no! If you told me I’d be doing coding and web app development 4 years ago I would have laughed at you. College classes that had me coding in notepad and some not so great experiences with the now dead s-controls left a bad taste in my mouth when it came to development. Then salesforce.com released Apex code and I saw how it could solve some of the problems we where facing. I taught myself the basics and the rest is history.

I also have a little blog related to all sorts of force.com goodness at tehnrd.com and some people follow around @TehNrd in Twitterland.

Q: What is your favourite type of development on the platform? What piece of work are you most proud of?

A: Databases design, triggers, and workflow are all cool but what I really like is building snazzy web apps. This has become even funner after jumping on the jQuery and jQueryUI bandwagon (disclaimer: I am a major jQuery fanboy). These JavaScript libraries allow you to make rich web apps with animations, drag & drop, and all sorts of other slick effects with minimal code. Pair this with Visualforce and the force.com database and you’ve got yourself a recipe for some great awesomesauce applications.

I think the coolest thing I’ve ever built on force.com was Gameforce. If anyone from salesforce.com reads this please don’t sue me for stealing your naming convention. Gameforce is a site built with force.com where you can play games. There is a single player black jack card game but what I think is even cooler is multiplayer Connect 4 and what I mean by multiplayer is two people on separate computers anywhere in the world. What I’m really proud of is this site is pure force.com. There is no flash, JavaScript, or any other tricks to handle the multiplayer game. You can check it out here.

Q: Where do you think “The Cloud” is headed?

A: I won’t even pretend to be the first person to say or think this, you talked about it here: http://tquilamockingbird.wordpress.com/2011/03/15/salesforce-com-crm-vs-oracle-ondemand/

But I really believe the younger generation will push adoption of the cloud to the next level. The CTOs and CEOs of today pick “the cloud” because it’s easy to manage, cheaper, and scalable. The CTOs and CEOs of tomorrow will choose cloud solutions for these same reasons but also because they know nothing else. Kids today use “the cloud” every day but don’t even realize it. Webmail, google docs, and mobile me to name a few. How many people under 20 use a local web client to check their personal mail, probably 3. How many people under 20 upload every picture they take to Flickr or Facebook and then don’t worry about the local copy, a lot. When it is time for these kids to choose solutions that solve business problems they will look to “the cloud” without even realizing “the cloud” is something new and useful. To them it will be their norm and the way things have always been.

Q: Which of the Spice Girls do you most closely identify with?

A: Of course the one living in UK has to work in a Spice Girls question. A secret fan you are perhaps? I’m not that scary and I’m not a baby. I don’t have red hair and I haven’t played organized sports in over 9 years. So in some strange way I think I just identified myself as relating the closest to Posh spice. Oh boy, I’m not going to be able to live this one down. I’m definitely not snobby or upscale but the other day someone said I had cool shoes so I guess that makes me stylish and poshy? Posh Dev!

Q: What advice do you have for beginners on the Force.com platform?

A: For beginners the Force.com Workbooks are a great resource. http://wiki.developerforce.com/index.php/Forcedotcomworkbook I am super jealous these didn’t exist when I first started. They are clear, concise, and walk you through the steps of building a full blown application. I also hear pretty good things about the Salesforce Handbook. apparently two guys that know a thing or two about salesforce.com and force.com development wrote it. The forums at developer.force.com are also a great place to hang out. When I first started doing force.com development the forums where the only resource available and the community helped me solve problems that ranged from the “simple face palm I can’t believe it was that easy” problems to the “holy smokes there is no way on earth I would have ever figured this out on my own” problems.

Q: Do you by any chance know of a better way to peel an orange?

A: Funny you ask because I actually do know the most superior method in the entire universe on how to consume an orange… http://www.tehnrd.com/the-best-way-to-eat-an-orange/

Written by Wes

March 16, 2011 at 3:25 pm

Client-Side VisualForce Pagination with Pajinate

with 9 comments

Pajinated DataTable

Pagination is an essential, and not so easy to implement user interface device that allows the developer to break long lists of items, or one very long item into sub-pages. I love the challenge that pagination brings (who doesn’t really) when developing efficient and reusable server-side code, but this article isn’t about that. Sometimes I need things done quickly, easily, and preferably with as little compromise as possible, and that’s what client-side pagination is all about. Read the rest of this entry »

Written by Wes

April 21, 2010 at 9:20 pm

Pajinate – A jQuery Pagination Plugin

with 234 comments

Pajinate is a simple and flexible jQuery plugin that allows you to divide long lists or areas of content into multiple separate pages. Not only is it a simpler alternative to server-side implementations, the time between paginated-page loads is almost nil (up to a reasonable page-size of course).

Pajinate - A pagination plugin the whole family can enjoy!

Read the rest of this entry »

Written by Wes

April 15, 2010 at 8:48 pm

Salesforce Form Validation Enhanced

with 56 comments

I have a dream, and in this dream form-validation is not a chore. All the nasty work is done client-side, and we – the developers – control what an error message says and where it says it! Server-side validation?! Pah, I spit in it’s general direction (but only if no ladies are present). I don’t need or want client-server round-trips.. I want speed, I want beauty, I want control; and I think you do too.

Our end goal: A neat, realtime, client-side validation technique for VisualForce.

Using either inputFields, Apex exception handling and/or the ‘required’ attribute in VisualForce, we have a number of mechanisms to deal with form-validation, but if we’re honest with ourselves, they’re the ten-thousands-spoons when all we need is a knife. I know you’ve heard me singing it’s praise from the rooftops, but yet again, jQuery is here to save the day. Read the rest of this entry »

Written by Wes

March 2, 2010 at 11:44 am