Thursday, 10 September 2015

Ride the Lightning with Trailhead

Ride the Lightning with Trailhead

There’s a Badge for that

LightingX, or Lightning Experience, the new Salesforce front end was launched on August 25th 2015 to great fanfare. 

When major new features or products come out there’s a requirement for skilling up existing administrators, developers, consultants and partners, as well as the huge number of users of Salesforce. Previously this has involved watching videos that were more often than not produced for internal Salesforce use or particularly focused on an upcoming event, such as Dreamforce. For Lightning X, Salesforce have chosen to use the incredibly popular training tool that is Trailhead to get everyone up to speed.

There are four new LightningX trails:

  • Admin Trail - Migrating to Lightning Experience
    for admins who will be enabling LightingX on the org they manage
  • Admin Trail - Starting with Lightning Experience
    learn how to administer LightningX
  • Developer Trail - Lightning Experience
    for developers to learn how to build apps for LightningX using Lightning Components or Visualforce
  • Sales Rep Trail - Using Lightning Experience
    for users starting with LightningX

These trails are proving hugely popular - at the Q&A with Parker Harris on August 26th 2015, one fact bomb that was dropped was that a LightningX badge was being earned every 15 seconds, which is pretty impressive.

Now obviously I’ve done all of the trails, as I can’t help myself when new badges come online. but as a career developer the developer trail was the most interesting and the one I’m going to look at in a little more detail.

Developer Trail - Lightning Experience

Screen Shot 2015 09 10 at 14 19 16

This is one of the longer trails - with suggested timing of 10 hours 35 minutes its not something you’ll be able to knock out over a lunch hour, but is a better candidate for a quiet Saturday or Sunday in the run up to Dreamforce. Don’t be put off by a longer time - that means that you’ll be learning chapter and verse rather than just skimming the surface, which is exactly what you need if you are going to be selling clients on the benefits of LightningX. It also doesn’t matter if you are looking to continue developing in Visualforce or moving on to Lightning components, as both of these are supported by LightningX and covered in depth in the trail.

The trail not only takes you through the technology, but also provides guidance as to whether you should be jumping in to develop with LightningX or if you should be holding off until things are a little more mature - crucial for those organisations that are debating if they should switch to the new UI. There are also steps for ISV partners and changes to existing development tools, so really something for everyone.

As well as Lightning Components and Visualforce, the trail also introduces the Lightning Design System (LDS) - kind of  a huge deal for those of us that have been trying to build apps that look like Salesforce without trying ourselves into scraped CSS files and the like. Once you’ve earned the badge you can get hands on with the LDS through my blog post on Lightning Design System - Edit Parent and Child Records

There are 5 badges available for this trail, and we all know that Badgier = Better, which brings me on to ...

Badgier - A Perfectly Cromulent Word

In the last blog post that I wrote on Trailhead, I used the word ‘badgier’, which generated more than a little interest online. I’ve been racking my brains to come up with another, equally cromulent, word to embiggen this post.

One of my favourite German words is ‘schadenfreude', often translated as ‘shameful pride’, which is taking pleasure in the misfortunes of others. Based on this I am coining the term ‘badgenfreude’, aka badge pride, which means taking rightful pleasure in your hard earned Trailhead badges. So give yourself a well-deserved dose of badgenfreude and get your LightningX badges with minimal delay.

Related Posts

  

Sunday, 6 September 2015

Lightning Design System - Edit Parent and Child Records

Lightning Design System - Edit Parent and Child Records

Screen Shot 2015 09 06 at 08 39 55

Introduction

Salesforce introduced the Lightning Design System as part of the new Lightning Experience UX at the end of August 2015. The Salesforce Lightning Design System (SLDS) is the first time that Salesforce have provided the developer community with the CSS, fonts and icons to allow us to build UI components that match the LightningX look and feel. This means no more fragile solutions that pull in the standard stylesheets or wholesale cloning of the standard stylesheets into static resources. In my case it also likely means the end of using Bootstrap for Salesforce1 applications, although as LDS is currently only at version 0.8 I’ll probably give it a few more versions before I move over completely.

After a browsing the docs I was keen to give the SLDS a spin and decided to combine this with another idea I’ve been toying with - taking some of my Visualforce solutions that I’ve blogged about and rebasing those onto Lightning components. So the first sample I’m going with is editing parent and child records on a single screen.

You can find the original Visualforce-centric post here - I haven’t gone for feature-parity with that post, specifically around creating and deleting child records, as there is enough to cover without that, although I may add that in a later version. As always, I’ve gone with the Account sobject as the parent and Contact as the children.

Getting Started with the SLDS

Screen Shot 2015 09 06 at 08 17 00

If you haven’t looked at the SLDS yet, the best place to start (as with so many things Salesforce) is by getting your Trailhead badge for the Lightning Design System module.

Designing the Screen

When working with Lightning Components I find its useful to sketch out the layout before starting the development - the greater the degree of granularity, the more reuse you are likely to get. This was made much easier in this case as I decided to use the LDS Master Detail Layout, consisting of the following components:

  • A page header
  • A list of cards for the account and contact records
  • A central form area to allow editing of the selected account or contact record

Here’s a screenshot of the completed page:

Screen Shot 2015 09 05 at 14 19 46

Once I had the basic layout I could start building the various components. I decided to go with a Lightning Application to host the page, as it meant I could navigate to it directly via a URL rather than having to build a navigation mechanism, which is a blog post all to itself!

Implementing the Application

There are quite a few elements to this solution, so I don’t intend to go through the code for all of them. The following sections detail some of the areas that I think are interesting - your mileage may vary - if there’s anything that I haven’t explained that you’d like to know more about, let me know in the comments and I’ll do my best to oblige. You can access the full codebase via the link to the Github repository at the end of this post.

The Application

The key part of the app markup is shown below:

<div class="slds">
    <c:BBAppHeader appEvent="{!c.appEvent}"/>
    <div class="slds-grid slds-wrap slds-p-top--x-small">
        <div class="slds-col slds-size--1-of-3 slds-p-around--medium">
             <c:BBAccountContactList account="{!v.account}"
                                     contacts="{!v.contacts}"
			             selectedContact="{!v.selectedContact}"
                                     editingContact="{!v.editingContact}" />
        </div>
        <aura:if isTrue="{!v.editingContact}">
            <div class="slds-col slds-size--2-of-3 slds-p-around--medium">
                <c:BBContactEditForm contact="{!v.selectedContact}" />
            </div>
        </aura:if>
        <aura:if isTrue="{! (!v.editingContact)}">
            <div class="slds-col slds-size--2-of-3 slds-p-around--medium">
                <c:BBAccountEditForm account="{!v.account}" />
            </div>
        </aura:if>
    </div>
</div>

The markup is wrapped in a div with the class ‘slds’ as the LDS is namespaced - so any styles that I use need to be inside an ancestor with this class or they will revert back to very ordinary looking HTML. 

The left and right components, are rendered inside an LDS grid, as I want to fix the size of each of them relative to each other.

The left hand component, the list of account and contact cards, takes up 1/3 of the available space, so is wrapped in a  div with the class “slds-size—1-of-3’ indicating that this div takes up one column out of a total of three available in the grid. The component takes an ‘editingContact’ attribute, which is set to true when the user clicks on a contact card and false when the user clicks on the account card.

The right hand component is wrapped inside a div with the class ‘slds-size—2-of-3’ indicating that it should take up two of the available three columns, or 2/3 of the available space. Depending on the value of the ‘editingContact’ attribute a form is rendered to allow the account or selected contact to be edited.  Note that I’ve enclosed each from in its own aura:if component - while I could use the ‘else’ attribute, I find it more readable to draw out the conditional rendering in this way. Note also that I’ve repeated the containing div for each conditionally rendered component - I could put this outside the aura:if components, but I’ve gone this route so that if I need to I can apply different styling to the containing div based on whether the user is editing the account or a contact, although at present the styling is identical. Note that I’ve also added a style class of ‘slds-p-around—medium’ to add some padding to the left and right components, otherwise they will butt up hard against each other.

URL Parameters

The id of the account to edit is picked up from the URL - I couldn’t find a mechanism for this that is provided by the Lightning framework, so I’m pulling it via a JavaScript method in the application's helper:

getURLParameter : function(param) {
	var result=decodeURIComponent((new RegExp('[?|&]' + param + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
        return result;
}

The application helper then retrieves the account and contacts for the ID via a server side request:

var action = cmp.get("c.GetAccountAndContacts");
var params={"accountIdStr":accountId};
action.setParams(params);
        
var self = this;
action.setCallback(this, function(response) {
    try {
        self.actionResponseHandler(response, cmp, self, self.gotAccount);
    }
    catch (e) {
        alert('Exception ' + e);
    }
});
$A.enqueueAction(action);

Note that I delegate the handling of the response from the server to a generic method - actionResponseHandler, which takes a parameter of the method that will actually handle the response - self.gotAccount in this case. This allows me to decouple all of the error handling around the request itself from the code that will process the response and update the data model. Note also that I pass the component itself, and the ‘self’ instance of the helper to the response handler - these are in turn passed to the gotAccount method so that when processing the response I can access attributes from the component or helper methods if I need to.

Component Event

The app header component takes an attribute of ‘appEvent’ that specifies a handler for a component event that is fired when the ‘Save' button in the header is clicked. As I plan to re-use the app header in the future, I don’t want to tie it to the expected behaviour of the page. Instead when the user clicks a button, an event is fired indicating the button that was clicked, which allows the containing application to decide what action to take. 

The app header declares the type of event that it will fire, and the name of the attribute that will contain the handler:

<aura:registerEvent name="appEvent" type="c:BBAppEvent" />

The ‘Save' button specifies an onclick handler:

<button class="slds-button slds-button--neutral" onclick="{!c.fireSaveEvent}">Save</button>

The handler constructs the event, specifies which button the user clicked and fires the event:

var appEvent = cmp.getEvent("appEvent");
appEvent.setParams({"action" : "save"});
appEvent.fire();

The containing app receives the event through its declared handler and saves the records to the server: 

appEvent : function(cmp, ev) {
    var action=ev.getParam("action");
    if (action=="save") {
        this.save(cmp);
    }
}

Two Way Attribute Binding

Aside from the event fired from the header component, two-way binding is used to “communicate’ updates between the various components. Using this mechanism means that any updates made to an account or contact in the editing form are also reflected in the account/contact list component, as references to the records are passed through the attribute binding. This means that the same variable instance is used in each component, so a change in one component is automatically picked up by any other component using that variable instance without any additional intervention on the part of my JavaScript.

SLDS Markup

If you aren’t used to CSS frameworks, SLDS can look like it introduces a lot of markup for containing divs etc and a lot of style classes, for example here’s a snippet from the app header:

<div class="slds-page-header">
    <div class="slds-grid">
        <div class="slds-col slds-has-flexi-truncate">
            <div class="slds-media">
                <div class="slds-media__figure">
                    <span class="slds-icon__container slds-icon-standard-account">
                        <c:BBsvg class="slds-icon" xlinkHref="/resource/BB_SLDS080/assets/icons/standard-sprite/svg/symbols.svg#account" />
                        <span class="slds-assistive-text">Account Icon</span>
                    </span>
                </div>
                ...
            </div>
        </div>
    </div>
</div>

All I can say here is that it becomes less jarring over time, as anyone who has spent time working with the Bootstrap framework can attest. One thing it does encourage you to do is to decompose your components as much as possible, to keep the amount of markup short and readable.

Github Repository

Related Posts

 

Monday, 31 August 2015

Dreamforce 15

Badge2

Brace Yourselves - Dreamforce is Coming

Dreamforce 15 is now just over two weeks away (or has already taken place if you are reading this after September 18th 2015).

A Different Experience #1

This year Dreamforce will be a rather different experience - my company, BrightGen, has a booth (#45) in the Customer Success Zone where we’ll be showcasing our BrightMedia appcelerator for Media Ad Sales. This is the first time since 2010 that I’ve had to man a stand at Dreamforce, which means that I can’t hang out in the Dev Zone as much as I usually would.

A Different Experience #2

I’m speaking, but not in the Dev Zone. Instead I’m giving a more business focused talk on how we are using Lightning Components in the BrightMedia mobile front end - Mobilize Your Media Ad Sales with Lightning Components. This is a 9am start on Wednesday 16th and takes place in the San Francisco Marriott Marquis Hotel, Foothill E. While this is a business focused talk, I’ll be able happy to go into detail on the technical side either after the talk or at the booth. Hopefully I’ll see a few of my regular readers there.

A Different Experience #3

The Dev Zone this year is getting a hefty dose of Trailhead. I’ve had a hand in a Quick Start or two which will hopefully make the cut, so if you are working through those see if you can spot any written in my inimitable style. 

Some Things Don’t Change

The Developer Keynote starts at 10:30 on Thursday 17th in Moscone Centre West and there’s no way I’d miss it, so I’ll be leaving the booth to the tender mercies of the Sales team for the duration. I can’t wait to hear the announcements, although they’ll have to go some to top the performance of Trailhead from last year.

  

Sunday, 23 August 2015

Certified Salesforce Platform Developer

Certified Salesforce Platform Developer

Screen Shot 2015 08 23 at 16 04 36

(As always with Certification blog posts, please don’t ask for answers or post actual questions in comments etc. Doing so breaches the test taker agreement and devalues the exam for everyone)

Introduction

As a Certified Salesforce Advanced Developer, I was offered the chance to participate in the Platform Developer II Certification in July 2015. Anyone who knows me knows I can’t resist a cert, so I jumped at the chance. 

As is the case for every beta I’ve taken part in, the beta is double the length of the regular exam both in terms of questions (120) and duration (4 hours). The basic premise is that you get more time so that you can give feedback on every question, although the fact that there are twice as many questions means that you have to be keep a close eye on the clock. Personally I take the view that its only worth providing feedback for questions that stand out, for both positive and negative reasons - saying that a question is fine doesn’t really add much or help the certification team.

Preparation

The Study Guides from the Salesforce Certification site give chapter and verse on what you need to skill up on for the exam. I focused on the Visualforce, Apex and Lightning Developer’s Guides, plus a refresher on the latest versions of the metadata and SOAP API. I made sure that I knew the order of execution like the back of my hand and the usual Apex best practice suspects of bulkification, the various aspects of unit tests and asynchronous mechanisms. I also paid special attention to oauth and the mobile SDK. 

The Exam

As always, the exam is proctored, either in person on on-line - I chose the on-line variant as I prefer to do exams from home. For the first time, I had the proctor interrupt the exam to ask me to reposition my camera, which took a few attempts and consumed some time, taking me past the four hours in the end.

What struck me about this exam compared to the original Advanced Developer certification was that it felt like I was reading  less code and evaluating more scenarios based on descriptions. That said, I wouldn’t read too much into this as it could be that the questions I received in the original exam were not overly representative but just happened to skew towards code.

Four hours is a long time to maintain focus, and the bonus of a beta exam is that you don’t receive the results immediately. Instead you have to wait a month or so until all the results and feedback have been assessed and collated. Its also difficult to call, as you don’t know which questions will make the final cut, so questions you found easy to get right might not count, whereas those that you struggled with may count against you.

Results

Obviously I passed or I wouldn’t be drawing attention to the experience with this post! As an existing Advanced Developer, passing Platform Developer II also confers Platform Developer I, so my certs count increases by two. Unfortunately, having achieved the new certs means I have to relinquish my Advanced Developer credential, so the net effect is a increase of one, taking me up to 9 x certified. As the number of certs increases its getting harder to catch them all, especially with the new Marketer credentials.

Final Thoughts

Four hours and 120 questions requires a considerable amount of effort, and wonder how useful the final hour or so actually is to the Salesforce Certification team, both in terms of the feedback (most questions will feel tough by then, due to fatigue if nothing else) and performance (I’d expect more incorrect answers towards the end, again due to fatigue). A better way to run these betas might be to break them up into two exams of two hours/60 questions. Beta candidates would still be required to answer all 120 questions, but not in one solid block. I suggested this as part of my exam feedback, so maybe something will come of this. 

Related Posts

Saturday, 8 August 2015

Trailhead - Bigger, Better, Badgier

Trailhead - Bigger, Better, Badgier

Screen Shot 2015 08 08 at 08 06 29

Introduction

Trailhead has received a major injection of new content in the run up to Dreamforce, and now boasts 30 projects, 7 trails and 6 projects.

If you haven’t used Trailhead yet (Seriously? What have you been doing with your free time?), take a look at my intro blog post to cover the basics.

New Trails

A number of trails have received additional content, but there are also two brand new trails to get tackle:

  • Admin Trail - CRM
    Up until now the trails tended to be focused on customisation or development of the platform side of Salesforce, but that’s no longer the case. This trail introduces the concepts of Accounts, Contacts, Leads and Opportunities, and takes you through configuring sobjects, creating records, setting up a sales process and assigning and converting leads. These are all key skills for administering a Sales Cloud implementation, so if you are thinking of taking your career in that direction its an excellent starting point
  • Dreamforce Trail
    A short trail, comprised of a single module with 3 steps. If you are going to Dreamforce for the first time this year, get the heads up on the general experience and specifics for admins and developers. I’ll be there again this year, but in a change of pace I’ll be manning a stand in the customer success zone so I won’t be able to spend the whole week in the dev zone as I usually do.

New Badges

There are 5 new badges available - 4 across the two new trails covered above, and one for the new Event Monitoring module.

Event Monitoring

Screen Shot 2015 08 08 at 08 11 00

 

  

This is a new module on the Intermediate Developer Trail, this is an example of why you should check back with Trailhead regularly - just because you completed a trail a couple of months ago doesn’t mean that’s still the case!

The Event Monitoring module is a shining example of another Trailhead benefit - it gets you working on aspects of the platform you might otherwise miss out on. The event log is something I’ve read about and answered questions on when maintaining certifications, but its not something that I’ve had reason to use up to now. This module not only gets into the details, but also has you working with the event log in your developer edition via the workbench.

Quick Starts and Projects

These aren’t new, but are something that I’ve only just picked up on. The quick starts are ideal if you want to get a rapid, hands on introduction to a particular area of the platform but you only have half an hour or so to spare. The projects require a more significant investment of time, and consist of a number of modules that layer on each other to build a full blown application.

Don’t Delay

There’s a lot of content on Trailhead already. and its only going to get bigger (and badgier!), so the sooner you get started the sooner you’ll have a plethora of badges to brag about on your social media channel of choice.

Screen Shot 2015 08 08 at 08 26 03

Related Posts

  

Sunday, 26 July 2015

Lightning Components and Custom Apex Classes

Lightning Components and Custom Apex Classes

Overview

This week I’ve been generating summary information in an Apex controller and surfacing this through a Lightning Component. When designing the solution, my initial thoughts were that I’d either:

  • have the component call multiple methods on the controller - not as inefficient as it sounds thanks to ‘boxcarring’, described in detail in Peter Chittum’s blog post.
  • return the results as a JSON string and parse this client side to access the details

However, after looking through the Lightning Components Developer’s Guide, a third way presented itself - the framework allows the Apex controller to return a instance of a custom Apex class, which is then automatically converted into a JavaScript object for use client-side.

Scenario

For the purposes of this blog post I have a simple use-case of returning the total number of Accounts, Contacts and Opportunities in the system. 

Code

The summary information is encapsulated in the RecordCounts custom Apex class, which also doubles as the Apex controller for the component, providing the GetRecordCounts method to retrieve the information. Note that the methods and attributes for use client-side have the AuraEnabled annotation:

public class RecordCounts {
    @AuraEnabled
    public Integer numAccounts {get; set;}
    
    @AuraEnabled
    public Integer numContacts {get; set;}
    
    @AuraEnabled
    public Integer numOpportunities {get; set;}
    
    @AuraEnabled
    public static RecordCounts GetRecordCounts()
    {
        RecordCounts result=new RecordCounts();
        result.numAccounts=[select count() from Account];
        result.numContacts=[select count() from Contact];
        result.numOpportunities=[select count() from Opportunity];
        
        return result;
    }
}

The lightning component is very straightforward - it defines that the Apex controller is ‘RecordCounts’, provides an attribute to store the retrieved record count instance in and has markup to output the value.  The information is retrieved from the server via the doInit event handler, which will be invoked when the component is initialised but before it is rendered. 

<aura:component controller="RecordCounts">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute type="RecordCounts" name="counts" />
    Number of accounts = {!v.counts.numAccounts}<br/>
    Number of contacts = {!v.counts.numContacts}<br/>
    Number of opportunities = {!v.counts.numOpportunities}<br/>
</aura:component>

Note that the type of the ‘counts’  attribute is defined as the name of the custom apex class - RecordCounts. Note also that I can simply access properties from the Apex class using the JavaScript object dot notation, as the record instance has been converted to a Javascript object representation.

In accordance with Lightning Components best practice, the component controller simply delegates to a helper for the init event callback handler:

({
	doInit : function(component, event, helper) {
		helper.doInit(component, event);
	}
})

while the helper executes the server side method and sets the Javascript object representation of the Apex class instance into the ‘counts’ attribute upon success without any intervention from me to process the result or translate it to something that the component can use directly, as this is all handled by the framework:

({
	doInit : function(cmp, ev) {
        var action = cmp.get("c.GetRecordCounts");

        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                cmp.set('v.counts', response.getReturnValue());
            }
            else if (state === "ERROR") {
                alert('Error : ' + JSON.stringify(errors));
            }
        });
        $A.enqueueAction(action);
    }
})

Adding this component to a Lightning application and executing it generates the following output:

Screen Shot 2015 07 26 at 14 19 21

Related Posts

 

Tuesday, 9 June 2015

Lightning Components and Unobtrusive JavaScript

Lightning Components and Unobtrusive JavaScript

Overview

Recently I’ve been experimenting with wrapping some of my existing HTML components as Lightning Components - you might have spotted my tweet around the multi-date picker :

Screen Shot 2015 06 09 at 07 57 17

When writing JavaScript I try to adhere to the principles of Unobtrusive JavaScript, specifically around the separation of behaviour from markup. This means that rather than using inline JavaScript of the form:

<button id=“clickme” onclick=“clicked();">Click Me</button>

I just provide the markup in HTML:

<button id=“clickme”>Click Me</button>

and then bind the click handler as part of JavaScript initialisation (usually via jQuery):

<script type="text/javascript">
  $(document).ready(function(){
    $(‘#clickme').click(clicked);
  });
</script>

The Code

Component

The component makes use of the jQuery JavaScript library:

<aura:component controller="UnobtrusiveController">
    <ltng:require scripts="/resource/jQuery_2_1_0"
                  afterScriptsLoaded="{!c.doInit}" />
    <button id="clickme">Click Me</button>
    <div id="results"></div>
</aura:component>

Controller

The controller contains a single method invoked after the jQuery library is loaded, which delegates to the helper:

({
	doInit : function(component, event, helper) {
		helper.doInit(component);
	}
})

Helper

The helper carries out the heavy lifting (such as it is in this noddy example), binding the click handler to the button and defining the function that will be executed in response to a click event, which executes a server side method in the Apex controller.

({
	doInit : function(cmp) {
		var self=this;
		$('#clickme').click(function (ev) {self.clicked(cmp, ev);});
	},
	clicked: function(cmp, ev) {
		var action = cmp.get("c.Method1");

		action.setCallback(this, function(response) {
			if (response.getState() === "SUCCESS") {
				$('#results').html(response.getReturnValue());
			} else if (a.getState() === "ERROR") {
				console.log("Errors", response.getError());
			}
		});
		$A.enqueueAction(action);
	}
})

Apex Controller

The Apex controller contains a single method that returns a string showing that it was executed.

public class UnobtrusiveController {
	@AuraEnabled
	public static String Method1()
	{
		return 'Method 1 called';
	}
}

Application

A minimal lightning application is used to surface the component.

<aura:application >
    <bblightning:Unobtrusive />
</aura:application>

The Challenge

Adopting this approach with Lightning Components brings an additional challenge, in that when I click on my button, nothing appears to happen.  As I’m not using Lightning all day every day, my initial assumption whenever this happens (and its usually correct) is that I’ve got something wrong about my action or response handler, but the error is being swallowed.  Usually a few lines of debug logging to the console will show this, so I update my helper accordingly:

clicked: function(cmp, ev) {
	var action = cmp.get("c.Method1");
	console.log('Action = ' + JSON.stringify(action));
	action.setCallback(this, function(response) {
		console.log('In callback response = ' + JSON.stringify(response));
		if (response.getState() === "SUCCESS") {
			console.log('Return value = ' + response.getReturnValue());
			$('#results').html(response.getReturnValue());
		} else if (a.getState() === "ERROR") {
			console.log("Errors", response.getError());
		}
		console.log('Updated results');
	});
	console.log('Enqueuing action');
	$A.enqueueAction(action);
	console.log('Action enqueued');
}

Note that I’m using JSON.stringify() to output the action - this is an excellent utility, although if there are any circular references it will fail. Clicking the button now shows the following output in the console:

"Action = {"id":"6;a","descriptor":"apex://bblightning.UnobtrusiveController/ACTION$Method1","params":{}}" app.js:35:0
"Enqueuing action" app.js:36:131
"Action enqueued"

so no errors, the code proceeded as expected, but no sign of the callback being executed.  Turning on debug logging on the server also showed no sign of the Apex controller.  

As this was happening the day after my Salesforce org had been upgraded to Summer 15, I started to wonder if something had gone awry there, but trying out some of my other lightning components in the same instance showed that this wasn’t the case. My next though was the jQuery library namespace interfering with the lightning framework, but enabling no conflict mode didn’t help either. I then executed the clicked() function upon initialisation:

doInit : function(cmp) {
	var self=this;
	$('#clickme').click(function (ev) {self.clicked(cmp, ev);});
	this.clicked(cmp);
}

This time everything worked as expected, and the page contents were updated when the action completed, and all expected debug appeared.

The Solution

The issue was something to do with the way that the action was created and queued. The obvious candidate was the fact that the event handler function was bound to the element via unobtrusive JavaScript, rather than binding a component controller method via markup. After some digging around in the Lightning Developer's Guide, it became apparent that by doing this I'd stepped outside of the normal component lifecycle, so there was nothing in place to execute the queued action once my method completed. In a situation where I didn’t need immediate feedback to an event this would be fine, as it would get ‘boxcar’-d with the next action(s) that the framework sent. However, in this case I wanted it to fire immediately.

Luckily the architects of Lightning have thought about this, step up “Modifying Components Outside the Framework Lifecycle” and specifically the $A.run() method, which ensures the framework processes any queued actions - kind of like Test.stopTest() processes all queued asynchronous methods when unit testing.  Changing my code to execute this after queuing the action meant that my action executed as expect:

console.log('Enqueuing action');
$A.enqueueAction(action);
console.log('Action enqueued');
$A.run();

Related Posts