Andy in the Cloud

From BBC Basic to Force.com and beyond…


Leave a comment

Winter’17: Using a Lightning Component from an Action

Screen Shot 2016-08-21 at 17.19.18Back in 2013 i wrote a blog post with a very similar name, How To: Call Apex code from a Custom Button. It continues to gather a significant number of hits. Its a common task as its good to first consider extending the Salesforce UI’s before building your own. The Custom Button approach actually still works very well in Lightning Experience and still for now has some benefits. However Lightning Experience is increasingly offering more and more ways to be customised, Home Page, Record Detail and now Actions!

Visualforce and Standard Controllers have long since been the main stay for implementing Custom Buttons. However for any of those that have tried it, you’ll know that Visualforce pages need some work to adopt the new Lightning Design System style. So what if we could link a natively built and styled custom Lightning UI with a button?

Well in Winter’17 we can! Custom Buttons are out in the Lightning world, what are hip and trendy these days are Actions, as i mentioned in my Platform Action post, Actions are fast becoming the future! Or in this case Lightning Component Actions.

Force.com IDE and Lightning Components

Screen Shot 2016-08-21 at 15.10.07.pngI have also used this as a chance to get familiar with the recently announce Force.com IDE Beta, which supports editing Lightning Components. It worked quite well, the wizard creates the basic files of a component include template controller and helper files.

The auto complete also worked quite well in the component editor. There is also quite a neat outline view. To create a design file (not actually needed here) i had to create this as a simple text file in Eclipse and be sure to name it after my component with .design on the end. After this the IDE seemed to pick it up just fine, though it found it does not save with the other component files as i would have expected.

Screen Shot 2016-08-21 at 18.33.54

Creating an Lightning Component Action

As with the Record, Tab and Home pages, a new interface, force:lightningQuickAction, has been added to the platform to indicate that your component supports Actions. I used the sample in the Salesforce documentation to get me started and it works quite well. The following is the component markup, i’ll cover the controller code later in this post.

<aura:component implements="force:lightningQuickAction">
<!-- Stupidly simple addition -->
<ui:inputNumber aura:id="num1"/> +
<ui:inputNumber aura:id="num2"/>
<ui:button label="Add" press="{!c.clickAdd}"/>
</aura:component>

What was not immediately apparent to me once i had uploaded the code, was that i still needed to create an Action under Setup for object i wanted my action to be associated with. I chose Account for this, the following shows the New Action page i completed. It automatically detected my Lightning Component, nice!

Screen Shot 2016-08-21 at 17.21.49

I then found My Action under the Layout Editor, which was also a little odd since i have become so used to finding my components in Lightning App Builder. I guess though the distinction is record level vs page level and hence the Layout Editor was chosen, plus existing actions are managed through layouts.

Screen Shot 2016-08-21 at 18.21.10.png

Once i updated the Layout,  My Action then appeared under the actions drop down (as shown at the top of this blog). As you can see below the component is wrapped in a popup with a system provided Cancel button. I chose to use the force:lightningQuickAction interface as per the docs. The force:lightningQuickActionWithoutHeader hides the Header and Cancel button shown, though popup close X button is still shown.

Screen Shot 2016-08-22 at 00.55.06

The Component Controller code for the sample component shows how you can programatically close the popup and deliver a user message via the toast component. I enjoyed learning about this while I looked at this sample. Extra credit to the documentation author here!

({
clickAdd: function(component, event, helper) {

// Get the values from the form
var n1 = component.find("num1").get("v.value");
var n2 = component.find("num2").get("v.value");

// Display the total in a "toast" status message
var resultsToast = $A.get("e.force:showToast");
resultsToast.setParams({
"title": "Quick Add: " + n1 + " + " + n2,
"message": "The total is: " + (n1 + n2) + "."
});
resultsToast.fire();

// Close the action panel
var dismissActionPanel = $A.get("e.force:closeQuickAction");
dismissActionPanel.fire();
}
})

Firing the toast event created in the above sample looks like this…

Screen Shot 2016-08-21 at 18.23.20

Context is everything…

The force:hasRecordId interface can be used to determine which record the user is looking at. Simply add it to your component like so…

<aura:component
implements="force:lightningQuickAction,force:hasRecordId">
Record Id is {!v.recordId}
</aura:component>

Note: I have it on good authority, that contrary to some samples and articles the you do NOT need to define the recordId property via aura:attribute.

Summary

In short i am really getting quite excited by the amount of places Lightning Components are starting to popup in, not just more places within Lightning Experience, but Salesforce1 Mobile, Communities and even Lightning Outlook. Join me at my Dreamforce 2016 session where we will also be looking at Lightning Out: Components on any Platform, featuring Google App Addins.


1 Comment

Help Salesforce help us, writing a good Idea Exchange post

IdeaExchangeIf there is one mantra that Salesforce has been driving home, its that its good to listen to your customers. Not only does the platform provide us with some excellent tools to engage with our customers. Salesforce also make sure they are providing tools, communities and events to listen to us!

When you put forward an idea, how often do you stop to think about what your responsibilities are? The obvious one is stating clearly what the idea is. After that, surely your idea is so good it needs no further perspectives? Right? Wrong!

The key to making it an idea Salesforce Product Managers can understand and support is giving them the information to fight your corner when they are allocating development resources ahead of each release. Them agreeing it is a good idea is not always enough to make it through. Developers even in Salesforce are a finite resource. So priority calls have to be made, especially when some ideas are not cheap to develop.

So what can we do to help Product Managers help us?

Screen Shot 2016-07-30 at 15.25.34.pngIdea Exchange is one such place where you can raise your ideas, socialise them and have others vote on them. You can read more about the Idea Exchange process and guidelines here. The sidebar shown on the Idea Exchange page allows you to review ideas implemented and those upcoming. Votes are of course important, but having a well formed idea is also equally important to getting it in front Product Managers and into internal discussions during planning. As per the Salesforce guidelines

“The minimum point threshold is to help us manage communication expectations only and does not factor in how we prioritize our road map. Product Managers can and do deliver Ideas of all point values big and small, it’s just that we can only guarantee status updates on Ideas that have the most community backing.”

Preparation and Perspective

Take some time to understand what has lead you to your idea. If your a developer or admin, what is the business process or user experience your trying to achieve and could not? How has the lack of whatever feature or facility you need impacted your customers or client? Remember Salesforce are thinking about the customer, as should you. Think about the following and try to answer in as quantitative way as possible.

  • What is the impact on the users productivity?
  • What common use cases are effected by not having this idea?
  • What is the impact on the build cost (e.g. more code and less clicks)?
  • What is the ongoing cost of any workaround?

Ensure your idea title can relate to as many people as possible

  • Keep your idea focused. You might feel there is a larger problem or concept being missed, but try to avoid letting this creep into your idea. Don’t just state the area of the idea in the title, e.g. “Process Builder – Criteria”.
  • Relatable by others. If your a developer or admin, try to make your idea relate to more than just your fellow developers or admins, keep the technical terms to a minimum. Instead of “Add X method to class Y” state “Ability to perform A from Apex”. You can always include code samples or ideas in the body of your idea. Try bouncing the idea off others for feedback before submitting.
  • Focus on the idea, avoid being to prescriptive. Unless its pretty clear its the only option, try to avoid preempting the solution to your idea in the title and focus on the idea itself in the title. If your to prescriptive you risk detracting from the problem and what the idea is about. Instead offer details on your thoughts regarding how Salesforce should implement your idea in your description.

Your description is your shop front, sell your idea!

Take a moment to understand the toolbar and the tools on it. Prepare what your going to say separately as you cannot edit what you post and preparing in the posting window can be risky if you accidentally close the browser window! IdeasToolbar.png

  • Structure your description and prioritise.
    Readers only have a limited amount of attention, so it is unlikely everyone will read your idea from top to bottom. So keep it short and try to tell a short story using your preparation above, bring the reader with you so they can better empathize with the problem being solved and thus your idea. Focus on the problem statement and qualification, then the idea, then additional thoughts or specifics that might help with further understanding or solving the idea.
  • A picture speaks a thousand words!
    Understand what the most visual striking way of expressing your idea is. If its a new button or field you want, consider a screenshot with some annotations on it.
  • Format and pretty print your code.
    Use the code toolbar button to include sample code. This highlights in a different way from your text. Make sure to get the spacing corrected, don’t force the reader to read through poorly formatted code.
  • Use hyperlinks to other resources.
    Link to community posts or StackExchange threads where other users are talking about the problem your idea solves. As discussed above try to inline pictures or code in the description, don’t force people to click through to read more about your idea. That said you might want to include a blog reference that goes into more detail, especially if you have included thoughts on workarounds that might help Salesforce in determining the options for implementing a your idea.
  • Encourage comments that add maximum value to supporting the idea.
    Finally in your description, encourage people to comment on the idea in ways that add value to your problem definition and impacts. Comments that say “+1” or “We urgently need this!” don’t really help. What you want is evidence from the community through brief testimonials or examples of how its impacting them or their users. This of course also applies if your reading this and comment on ideas as well. You can also comment on your own ideas to give updates or further thoughts.

Socializing and monitoring your idea

  • Use your social network for sure. I think its also fine to retweet to ask for more support every few months or so, just don’t over do it. Also if you happen to know who the Product Manager is for an area, say on Twitter for example. Then helping by drawing their attention to your idea is also something you can consider, just be polite and professional when you do!
  • If you have a blog and or write answers on Success Community or StackExchange provide a link to your idea as well. Try to do this at the top and bottom of what ever peace your writing, again not everyone reads till the end!
  • Don’t spam people with your idea, that can have a negative effect.
  • While adding a link to your idea to an existing blog or community post is also a good idea, do make sure it’s relevant.
  • You’ll get email notifications each time someone posts a comment on your idea. Consider reaching out to them if you think they can add more detail or further support your idea.

At the end of the day….

I’m aware there is sometimes skepticism about Idea Exchange and thus people either don’t post to it or when they do they don’t put in enough effort to frame their idea. At the end of the day its up to you if you feel its worth the effort vs the reward. I know many of the Salesforce Product Managers really value the type of information i am describing in this blog and thus has been one of the drivers behind writing it.

The other thing I do know, through working in an ISV myself. Is if someone has clearly put in the effort to frame and idea vs a short blast, the idea is much more likely to get considered than not. Especially if it contains information that makes the Product Managers job easier by providing use cases and impact analysis they can use internally during resourcing and priority discussions.


6 Comments

Introducing the Flow Factory

Flow is a great technology for providing a means for non-coders to build functionality. More so than any other point and click facility on the platform, even Process Builder. Why? Because it offers a rich set of Elements (operations) that contain conditional branching, loop and storage of variables. Along with the ability to read or update any object (API accessible) you like. Its almost like a programming language….

Ironically, like Apex, it is missing one increasingly asked for feature… being able to call another Flow that is not known at the time your writing your calling code. Such as one configured via the amazing Custom Metadata… Basically a kind of Apex reflection for Flow. Often the workaround for this type of problem is to use a factory pattern.

As i highlighted in this prior blog on calling Flow from Apex, the platform does not yet provide this capability to change this please up vote this idea. Well at least not in Apex, as there exists a REST API for this. Meanwhile though back in the land of Apex, it occurred to me when building the LittleBits Connector last year. As workaround i could generate a factory class that would workaround this.

I have created Flow Toolbelt library (GitHub repo here) and package (if you want to install that way) which takes last years solution and lifts it into its own smaller package. The Flow Factory tab discovers the Flows configured in your org and generates the required factory Apex class. If you add or remove flows you need to repeat the process.

FlowFactory.png

Once this has been Deployed you can use code like the following. Passing in the name of your Flow. Note this is a WIP version of the library and needs more error handling, so be sure to pass in a valid Flow name and also at least an empty params Map.

Flow.Interview flow =
  flowtb.FlowFactory.newInstance('TestA', new Map<String, Object>());
flow.start();
System.debug(flow.getVariableValue('Var'));

I think this concept can be extended to allow Flow to run from other Apex entry points, such as the recently added Sandbox Apex callback. Allowing you to run Flow when your Sandbox spins up. Let me know your thoughts, if this is something useful or not.

 

 


Leave a comment

Working with Apex Mocks Matchers and Unit Of Work

The Apex Mocks framework gained a new feature recently, namely Matchers. This new feature means that we can start verifying what records and their fields values are being passed to a mocked Unit Of Work more reliably and with a greater level of detail.

Since the Unit Of Work deals primarily with SObject types this does present some challenges to the default behaviour of Apex Mocks. Stephen Willcock‘s excellent blog points out the reasons behind this with some great examples. In addition prior to the matchers functionality, you could not verify your interest in a specific field value of a record, passed to registerDirty for example.

So first consider the following test code that does not use matchers.

	@IsTest
	private static void callingApplyDiscountShouldCalcDiscountAndRegisterDirty()
	{
		// Create mocks
		fflib_ApexMocks mocks = new fflib_ApexMocks();
		fflib_ISObjectUnitOfWork uowMock = new fflib_SObjectMocks.SObjectUnitOfWork(mocks);

		// Given
		Opportunity opp = new Opportunity(
			Id = fflib_IDGenerator.generate(Opportunity.SObjectType),
			Name = 'Test Opportunity',
			StageName = 'Open',
			Amount = 1000,
			CloseDate = System.today());
		Application.UnitOfWork.setMock(new List<Opportunity> { opp };);

		// When
		IOpportunities opps =
			Opportunities.newInstance(testOppsList);
		opps.applyDiscount(10, uowMock);

		// Then
		((fflib_ISObjectUnitOfWork)
			mocks.verify(uowMock, 1)).registerDirty(
				new Opportunity(
					Id = opp.Id,
					Name = 'Test Opportunity',
					StageName = 'Open',
					Amount = 900,
					CloseDate = System.today()));
	}

On the face of it, it looks like it should correctly verify that an updated Opportunity record with 10% removed from the Amount was passed to the Unit Of Work. But this fails with an assert claiming the method was not called. The main reason for this is its a new instance and this is not what the mock recorded. Changing it to verify with the test record instance works, but this only verifies the test record was passed, the Amount could be anything.

		// Then
		((fflib_ISObjectUnitOfWork)
			mocks.verify(uowMock, 1)).registerDirty(opp);

The solution is to use the new Matchers functionality for SObject’s. This time we can verify that a record was passed to the registerDirty method, that it was the one we expected by its Id and critically the correct Amount was set.

		// Then
		((fflib_ISObjectUnitOfWork)
			mocks.verify(uowMock, 1)).registerDirty(
				fflib_Match.sObjectWith(
					new Map<SObjectField, Object>{
						Opportunity.Id => opp.Id,
						Opportunity.Amount => 900} ));

There is also methods fflib_Match.sObjectWithName and fflib_Match.sObjectWithId as kind of short hands if you just want to check these specific fields. The Matcher framework is hugely powerful, with many more useful matchers. So i encourage you to take a deeper look David Frudd‘s excellent blog post here to learn more.

If you want to know more about how Apex Mocks integrates with the Apex Enterprise Patterns as shown in the example above, refer to this two part series here.


20 Comments

Declarative Rollup Tool Summer Release!

Over the course of the last couple of weeks, i have been focusing my community time on release v2.4 of the DLRS tool. Specifically focusing on some much requested features driven by the community in the the Chatter group.

So lets get stuck in…

Rollup Scheduler Improvements

The ability to run a full (or partial with criteria) recalculate of a rollup on a daily schedule has been in the tool for a few releases now. However up until now the only option was to run it at 2am everyday. It is now possible to change this with this new UI, its a bit raw and basic, but for now it should at least give some more flexibility.

RollupSchedule.png

Support for Merging Accounts, Contacts and Leads

The platform has some special handling for merging Accounts, Contacts and Leads. Especially when it comes to when Apex Triggers are invoked. Basically if your parent object is one of these objects, prior versions of the tool had no awareness of this operation, so rollups would not recalculate. If you are using Realtime or Schedule calculation modes on your rollups. Since the platform does not fire Apex Triggers for child records reparented as a result of a merge.

With this release there are two things you can do to fix this. First when you click the Manage Child Trigger button, you get a new checkbox option to control deployment of an additional Apex Trigger on the parent object. If your upgrading you will need to click Remove then Deploy again, to see this.

ParentTrigger.png

IMPORTANT NOTE: If you don’t feel merge operations are an issue for your use cases you can deselect this option and cut down on the number of triggers deployed. Also if it is only the rollup child object that supports merging, there is no need to deploy any additional triggers and the tool does not show the above checkbox option.

Secondly you need to setup the RollupJob as an Apex Scheduled job (under Setup > Apex Classes), even if you don’t have any Schedule Mode rollups. This is due to the fact that due to a platform restriction, the tool cannot recalculate rollups realtime during a merge operation. So it can only record that they need to be recalculated. It does this via the tools scheduled mode infrastructure, by automatically adding records to the Lookup Rollup Summary Schedule Items object. Note that you don’t need to change your rollups from Realtime to Scheduled mode for this to work, only schedule the job.

Support for Archived / Deleted Records via the All Rows Setting

Salesforce archives Tasks and Events after a while. If you have rollups over these child objects you can enable the Aggregate All Rows checkbox. This will ensure your rollups remain accurate even if some records have been archived. Note this also will apply to records in the recycle bin. For upgrades (if your not using the Manage Lookup Rollup Summaries tab), you will need to add this field to your layout to see it.

AllRows.png

Row Limit for Concatenate and Last Rollup Operations

If your using the Last or Concatenate operations, you can define a limit as to how many child records are actually considered when calculating the rollup. This is useful if your using Concatenate into a fix length field for example. When upgrading you need to add the new Row Limit field to your layout if your not using the swanky new Manage Lookup Rollup Summaries tab.

RowLimit.png

Improved House Keeping for Scheduled Mode

If your are using rollups with their Calculation Mode set to Scheduled. The tool records parent rollup records to be later recalculated by the RollupJob Apex Scheduled job. In past releases if through merge or other operation the parent record was deleted before the next scheduled run. Then records would sit in limbo in the Lookup Rollup Summary Schedule Items object, being processed and erroring over and over. These will now be cleared out and there is no upgrade actions you need to take for this.

Summary

Thanks for everyones support for this tool, i hope these changes help you go further with clicks not code! Though as reminder please keep in mind the best practices and restrictions listed in the README. If you have any questions you can either post comments on this blog or use the Chatter Group. The Chatter Group is a great place to get your query seen by a broader group of people who are also diligently supporting the tool as well!

You can find releases of the tool here.


2 Comments

Lightning Out: Components on Any Platform

This blog is my first video blog! Since Salesforce does not record the Developer Theatre sessions at the Salesforce World Tour events i thought i would do a re-run at home of my session last week and publish it here. As you know i have a love for all things API’s, and while I typically focus in this blog on backend API’s, there is one i’ve been keen to explore for a while…

The Lightning Out API, as any good API should, brings great promise and reality i’m pleased to say, to further integrating and extending the power of the platform and generally simplifying our users lives. In this case boldly going where no Lightning Component has gone before….

You can access the slides and thus the links within via this Slideshare upload.


7 Comments

Introduction to the Platform Action API

shutterstock_159003926.jpg

Actions are Salesforce’s general term for tasks users can perform either through buttons throughout various UI’s on desktop, mobile, tablet etc or in fact via non-UI processes such those built via via Process Builder or Automation Flows.

Actions are about “getting things done” in Salesforce. They encapsulate a piece of logic that allows a user to perform some work, such as sending email. When an action runs, it saves changes in your organization by updating the database. More here.

Over the years we’ve had many terms and ways to define these. Custom Button and Custom Link are perhaps the most obvious ones, which i’ve covered here in the past. Quick Actions (previously Publisher Actions) and more recently we’ve had Action Link‘s, which i covered in a past blog. Then of course the Standard Buttons, Edit, Delete, Follow, Submit for Approval etc provided by the platform. Such actions appear in various places Record layouts, List Views, Related Lists, Chatter and more recently Flexi Pages (aka Lighting Pages).

You might wonder then, if you had the task as developer to build your own UI or tool that wanted to expose some or all of the above actions, it would be quite a challenge to find them all. Indeed in some cases you may have had to resort to URL hacking to invoke some of them. Well worry not no longer, Salesforce’s clever architects now have you covered! Enter a new virtual SObject known as PlatformAction! Before we get onto what exactly virtual means, lets review some Actions and some SOQL queries…

Consider this Account Record detail page in the Classic (or Aloha) UI

PlatformActionAccount.png

Note down your record ID and use it in a query like the one below…

SELECT DeviceFormat, Label, Type, Section,
       ActionTarget, ActionTargetType, ActionListContext
  FROM PlatformAction
  WHERE ActionListContext = 'Record' AND
        SourceEntity = '001B000000D2V0n' AND
        Section = 'Page' AND
        DeviceFormat = 'Aloha'

In Developer Console you should see something like this…

PlatformActionQueryResults1.png

Pretty cool huh!? Check out the ActionTarget field, for the Standard Button records, thats the URL you can place on your UI’s to invoke that action, simple as that! Better still this is a supported way to get it, no more URL hacking! Now lets add a couple of Custom Buttons and re-run the query…

PlatformActionAcount2.png

We now see CustomButton records appear…

PlatformActionQueryResults2.png

This next query reveals actions shown on a List View. I did note Custom List View buttons that require record selection did not appear however. I suspect this is due to them requiring more than a simple HTTP GET URL to invoke.

SELECT DeviceFormat, Label, Type, Section,
       ActionTarget, ActionTargetType, ActionListContext
  FROM PlatformAction
  WHERE ActionListContext = 'ListView' AND
        SourceEntity = 'Account' AND
        Section = 'Page' AND
        DeviceFormat = 'Aloha'

Other observations..

  • Prior to Summer’16 (out in preview as i write this), Apex SOQL was not supported, only REST API SOQL. This is due to a limitation with the internally applied LIMIT keyword. This has now been resolved in Summer’16, so Apex SOQL now works!
  • SourceEntity can also be given an SObject API name, e.g. SourceEntity = ‘Account’, the result here are object level buttons, like New or those you add to the MRU page.
  • DeviceFormat field value matters, if you leave it off, it defaults to Phone. Thus some actions will be missing from those in Desktop (Lightning Experience) or Aloha (Classic). I eventually found Custom Buttons using Visualforce pages that didn’t have the Lightning Supported checkbox set didn’t appear when querying with the Phone device type for example.
  • User context matters, actions returned are user and configuration sensitive, meaning the record itself, record type and associated layout all contribute to the actions returned. Custom Buttons for example need to be on the relevant layout.
  • Label and Icon information, there are also fields that allow you to render appropriate labels and icons for the actions.
  • Related List actions, you can also retrieve actions shown on related lists, search for RelatedList in the help topic here.
  • Describe actions? You will notice some actions have an ActionTargetType of Describe? These are invoked via an API, something i will cover in later blog.

So lets discuss the “virtual SObject” bit!?!

Your probably wondering what a virtual SObject is?

Well my best guess is its an SObject that is not backed by physical data in the Salesforce database. If you check the documentation you’ll see fields just like any other object and it supports SOQL (with some limitations). My thinking is the records for this object are dynamically generated on demand by doing all the heavy lifting internally to scan all the various historic places where actions have been defined.

Thank you Salesforce architects, this is now my #1 coolest Salesforce API!

Whats next?

  • For starters, no more URL hacking of those standard pages, no excuses now!
  • Helper class or Visualforce and/or Lighting component for actions?
  • Explore the Force.com Actions Developer Guide
Follow

Get every new post delivered to your Inbox.

Join 443 other followers