HOW TO: CALL AN APEX CONTROLLER METHOD FROM LIGHTNING COMPONENT

Lightning seems to be all the rage these days!  How could it not?  It is exciting stuff and changes the way that Salesforce developers need to think when coming up with their solutions on the platform.  One of the most common things you will need to do with Lightning will be to call methods on an Apex controller for any server side logic you need to perform.

If this is something you are trying to figure out then you have come to the right place.  If you are familiar with using Javascript Remoting in Visualforce, then calling Apex methods from a Lightning component will look very very similar.

The following assumes you have your namespace setup and you are able to create a Lightning app that you can hit from the preview in the developer console.  Once you have a Lightning app created, you can create a component to add to the app.  This component will be what makes the callout to the controller.

1
2
3
4
<aura:component controller="yournamespace.YourController">
    <aura:attribute name="yourAuraVariable" type="String"/>
    ...
</aura:component>

Here you can see that we have a controller called YourController.  This controller will have the method that we use to populate the aura attribute yourAuraVariable.  The controller code will look something like this.

1
2
3
4
5
6
public class YourController {
    @AuraEnabled
    public static String getMyAuraVariableFromTheController() {
        return 'Here is the text from my controller';
    }
}  

Now that we have our controller code built, it is just a matter of calling this code from a little bit of Javascript in the Lightning component.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
({
    getMyAuraVariable : function(component) {
        //this will be the method name on the controller contained within the
        // controller property on our aura component
        var a = component.get("c.getMyAuraVariableFromTheController");
        var self =this;
        //build the callback since all controller calls are batched and sent
        //asynchronously
        a.setCallback(this, function(action){
            //action.getState() will let you know if it was successful or not.
            //a good idea would be to check this to make sure everything
            //worked as expected.
            console.log(action.getState());
            //set the return value from the controller to the variable on our component
            component.set("v.yourAuraVaraible", action.getReturnValue());
            //do more stuff
        });
        //fire off the action
        $A.enqueueAction(a);
    },
    ...
})

This bit of code is contained within the helper of our component.  You simply call this function from anywhere, either on init or another action on the page and it will populate our aura variable with the results that are returned from the controller.  In this case ‘Here is the text from my controller’.  Obviously in most cases you will want to return more complex data than just a string but this is just to get you off the ground and running with how calling controller methods work.  Good luck and let me know if you have any questions!!

Posted in Technology | Tagged , , , , | Leave a comment

HOW TO: CALL BATCH APEX FROM BATCH APEX

Batch Apex is a powerful tool that can be used to do all sorts of cool stuff on the Salesforce platform.  Batch Apex is typically used to perform larger operations that would normally be restricted by governor limits.  It allows you to break that larger operation up into smaller bite-size chunks that are easier to deal with.

Since batch jobs are meant to deal with one query and processing records from that query, there may be times when you want to spin off another batch job when one is complete to finish your processing.  An example of when you might want to do this would be if you needed to perform a batch job to delete thousands of records but once those records were deleted, you need to create thousands of records based off of another query or object.

Starting a batch job from a batch job is fairly straightforward.  The key is placement of the code that actually starts the new batch.  The code that starts the new batch needs to be placed in the finish method of the initial batch.

1
2
3
4
globalvoid finish(Database.BatchableContext BC){
    //Add your start code for the other batch job here
    Database.executeBatch(new YourOtherBatchClass());
}

That’s pretty much it.  Calling executeBatch from the finish method of one batch job will kick off the new batch job.  There are a lot of fun things you can do with this.  One thing I have done has been to create a recursive batch job that calls itself.  If you are ever in a situation where you need to call a batch from a batch, I hope this helps!

Posted in Technology | Tagged , , , | Leave a comment

HAVING TROUBLE WITH ANIMATIONS IN IOS?

I was recently doing a lot of animations for a couple of iOS apps I was building.  For the most part, programming animations for iOS is straightforward and work really well.  I kept running into some small issues that were really bugging me and I was unable to find the answer to my issue.

The issue I was having was using the UIView animateWithDuration method.  I was taking a few views on my interface and moving/resizing/changing their alpha.  The method is pretty straightforward.  You basically call the method, tell it what you want the views to be when the animation is complete and set some other parameters.  Here is an example:

1
2
3
4
5
6
[UIView animateWithDuration:0.5 delay:0.1
                            options: UIViewAnimationCurveEaseIn animations:^{
                                [self.viewSample setFrame:CGRectMake(-100, self.viewSample.frame.origin.y, self.viewSample.frame.size.width, self.viewSample.frame.size.height)];
                            }
                         completion:^(BOOL finished){
                         }];

This animation will take the sampleView and move it to to an x coordinate of -100 so it moves off the screen.  The problem I was having with this is it would appear to move off the screen correctly but then pop back to it’s original position.  As it turns out, this issue is due to AutoLayout being checked for the ViewController.  Since -100 is not within the constraints of a valid view, AutoLayout takes over and tries to rearrange the views for you.  This was obviously not what I wanted but was glad to see that simply not using AutoLayout on the ViewController fixed the issue.

If you run into this issue, try not using AutoLayout and your problems should be solved!!

Posted in Technology | Tagged , , , | Leave a comment

REALTIME TRACKING WITH THE STREAMING API

At Dreamforce 2014 I had the opportunity to present some cool code on using the Streaming API to perform realtime tracking within VisualForce pages on Salesforce.  It was a great experience!  If you have been wondering how to use the Streaming API or how to incorporate Google Maps into VisualForce, check out the recording of the session and leave your comments below.

 

Posted in Technology | Tagged , , , , , | Leave a comment

HOW TO SETUP YOUR SALESFORCE ORGANIZATIONS

If is always hard to decide within a business how many Salesforce organizations there should be.  There are so many different factors at work within each business that will make the outcome unique for each company.

Here are three basic questions that we have come up with to help jump start the important pieces of this conversation.

1) Do I need a
a) Single Global Organization?
b) Set of Organizations by Region?
c) Set of Organizations by Business Unit?

2) How many pieces of the typical Salesforce environmental architecture do I need to support each individual organization?

3) What source control tools will I use to manage my Salesforce environments?.

Question 1
This question gets you thinking about your business in detail.  If you are a smaller business that only works in the United States, then you should be able to do everything in one org so this question will be easily answered.  As the size of your business increases, the number of business units multiple and your presence across the globe widens this becomes a very important conversation.  You will need to talk about languages, number formats, business processes, speed of new features, reporting roll-up, portals/communities and license cost considerations.  Sometimes the way organizations get structured just ‘sort of happens’ over time.  But once a company makes a strategic investment in the Salesforce platform this question should be discussed at all levels of the company.

Question 2
This question gets into discussions about…
a) How many sandboxes should be used?
b) How are code changes promoted through the sandboxes of an organization?
c) Who is in charge of the changes at each level: Business Analyst, Developer, Release Manager or IT?
d) How are changes to the system documented?  Are they through change sets?  Deployment log files?  Google Docs?

Question 3
This last question is pretty specific, but there are a lot of options.
a) Are you going to rely on Salesforce to be the main backup for your code?  Salesforce will guarantee backups of production database, but not for your sandboxes.
b) Are you going to use a separate source control tool like SVN or GIT?
c) Are you going to force developers to check out metadata files?
d) Are you going to do a nightly batch commit in the background that will not get every change, but will get the bulk of the metadata changes for that day?

Just knowing a few solid questions to ask will frame the conversation to get you to your critical decision points.  There are no right and wrong answers up front.  The answers for your specific company will only come after many detailed and important conversions.

Good luck!  Let us know at Sundog if we can ever help you during these discussions.  These are some of the best and most important discussions of any new implementation.

Posted in Technology | Tagged , , | Leave a comment

HOW DO YOU TIE YOUR FILES TO SALESFORCE? AZURE? SHAREPOINT?

Back in July, 2013 I wrote a whitepaper, Salesforce – Where to Save my Files?, detailing a couple of options for storing your files outside of Salesforce.  I really enjoyed exploring some very specific ways on how to save files to Box or Amazon’s S3 service.  To recap, the reason why you might want to save your files outside of Salesforce is because you only get so much space for files and that space is based on your number of licenses.  This link describes all the details but basically for an Enterprise org you get 11GB of file storage just for having your Salesforce org and then you get 2GB of file storage for every license.  This may seem like a lot, but you need to take into account how your files will grow over time.  For example let’s say you have 20,000 accounts and each account receives a 500KB PDF report every year.  So for just one year that will take up 20,000 x 500KB = 10,000,000KB = 10,000MB = 10GB.  If you only had 10 licenses, you would have 31GB of storage space, so you can see how quickly your file storage space would run out.  Note that you can purchase more file storage space from Salesforce separately.

Of course, the decision to keep these files outside of Salesforce should not be taken lightly.  The ability to control access to these documents with standard Salesforce security makes life very easy.  The ability to full-text search documents saved as Chatter Files or in Salesforce Content is also a great benefit.  One limitation to keep in mind with Salesforce Content is that you can have up to 2000 libraries.  If you were thinking of creating library for each account, that usually will not work.  But in the end, sometimes there are just too many files to store and the expense of having them in Salesforce will not overcome the other benefits.

So this leads us back to my whitepaper where even two years ago putting these files in Box of Amazon S3 were really solid options.  A couple of recent links about Amazon S3 are theAmazon Toolkit which allow for native hooks in Apex for working with AWS S3 and EC2 and an AppExchange product called Cloudpond S3 Connector recently build to do the AWS S3 integration for you.

With both of those options a folder was created in Box or S3 with the Salesforce ID as the name of the folder.  That works well and is very clean.

I could also envision an integration where the file is pushed to Box or S3 and then the URL is returned and that link is saved as a Chatter link or a link in Salesforce Content.  That type of solution would be the best of both worlds in a certain sense because the file itself would be kept outside of Salesforce, but the access to the link could be controlled by standard Salesforce security.

Another couple of options that have caught my eye recently are saving the files to Sharepoint and Microsoft Azure.

This article, Salesforce connects SharePoint files to its cloud with new tool, is really exciting, because it goes straight after solving this problem.  The files are saved in Sharepoint, but they can be accessed through Salesforce with no custom coding.  Here are links from Winter 2015 Release Notes and the Salesforce Files page.

Another option I have seen is to store all of the files in an Azure Blog Storage.  This type of storage can be very cost effective and can leverage Azure’s infrastructure in the cloud.  But anything involving Azure would involve a custom built solution that must be supported.  From Salesforce a Canvas App or web service integration could be used to get to the files stored on the Azure Blog Storage.

What have you seen for ways to solve this common enterprise problem?

Happy Integrating!

Posted in Technology | Tagged , , | Leave a comment

STOPPING A VISUALFORCE COMMAND BUTTON FROM FIRING THE CLICK EVENT TWICE – PART II

Back in September of 2013 I wrote this blog post, Stopping a Visualforce Command Button from Firing the Click Event Twice, about how to stop a Visualforce page button from posting back to the controller twice if the user double-clicks on it.  The solution that I presented works in a certain situation and the other solutions posted by others also help.  But I ran into a new use case where that solution does not work.

The scenario where my previous solution does not work is if the action behind the button has the potential to return an error or validation message.  The problem is that the button will now be disabled when the message is displayed so the user will not be able to click the button again.  As another potential solution I was wondering if we had the button call an apex actionFunction instead.  In this case the button could be disabled because we could make it enabled again by using the oncomplete attribute of the actionFunction.

But I came across another way of doing this by just having some Javascript not allow the button to be clicked again for a couple of seconds after it is clicked.  Here is how it works:

1) Create this Javascript at the top of your Visualforce page between some script tags

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var waitTime = 1;      
var countDown = waitTime+1;
var clickAllowed = true;
        
function stopDoubleClick(){       
    countDown=waitTime+1;           
    if(clickAllowed==true){
        clickAllowed=false;
        runCountDown();
        return true;
    }else{
        return false;
    }
}
function runCountDown(){       
    countDown--;           
    if(countDown<=0){
        clickAllowed=true;
    }else{    
        window.setTimeout(runCountDown,1000);
    }
}

2) Then in your commandButton call the stopDoubleClick() javascript function

1
<apex:commandButton onclick="return stopDoubleClick();" action="{!doWork}" value="Take Action"></apex:commandButton>

That solution has worked out pretty well.  I have tried to click a whole bunch of times and I never get a duplicate call on my controller.  But it is always hard to rely on a timing mechanism.

If you have an easier or better solution please let everyone know!  I even wish Salesforce would make an attribute or present a best practice on how to do this consistently.

Happy Visualforcing!

Posted in Technology | Tagged , | Leave a comment

EXTEND YOUR BRAND VOICE TO UNEXPECTED PLACES

For many organizations, it’s really challenging to master voice and tone.

Branding efforts often (justifiably) focus on strategy, archetypes, visual systems, brand standards and related areas. They’re necessary elements, and they’re usually easier to wrangle. As a result, solidifying voice and tone standards can receive less attention.

And even when voice and tone guidelines are clearly defined, it’s a seemingly endless effort to ensure they’re implemented across your various customer touchpoints. It’s one thing, for example, for product or service pages to reflect your desired voice and tone. It’s another, however, to extend your standards to success messages, confirmation emails, help pages, third-party applications and customer service communications (among others).

The enormity of the voice and tone effort makes brands like MailChimp even more impressive. They’ve adopted a “one voice, many tones” philosophy that’s simple, clear and accessible.Kate Kiefer Lee of MailChimp writes and speaks extensively on this topic, and they even freely share their voice and tone guide.

Today I discovered yet another great example from MailChimp. I was performing some quick research on the meta description practices of various brands, which involves peeking at the source code of their websites. Here’s what lurks “under the hood” of the MailChimp homepage:

 

MailChimp source code

 

It’s a witty, geeky example of discovering the MailChimp brand in the most unexpected places. The MailChimp voice, after all, is “fun but not childish” and “clever but not silly.”

Where (and how) can your content delight your audiences in similar ways?

To learn more, read these posts from Kate Kiefer Lee:
Tone and Voice: Showing Your Users That You Care
Vulnerable Branding: Keeping your company’s voice honest
Don’t Poke the Bear: Creating Content for Sensitive Situations

Posted in Technology | Tagged , , | Leave a comment

SALESFORCE CUSTOM LEAD CONVERSION

Lead conversion in one sense is a pretty simple concept.  You define when the lead should be converted, the user clicks the ‘Convert’ button and voila, you have a new Account/Contact/Opportunity that mapped a whole bunch of fields for you automatically.  The really cool part with the declarative ( Point-n-Click ) piece of Salesforce is that you can control the mapping of your fields by clicking on the ‘Map Lead Fields’ button on the page that lists the fields for the Lead object.

Great!  But what if your business requirements are not that simple?

What if you want to change some values before the lead conversion occurs?  What if you want to do different actions during the lead conversion depending on the record type of your lead?

At first glance we could try to do something with a workflow rule and/or a trigger.  These are great thoughts as we always want to try to use the declarative power of Salesforce first, but we cannot get in via these methods to modify the lead if the standard ‘Convert’ button has been clicked.  Even a concept as simple as saying I want a specific field to be filled during the ‘Convert’ process is kicked off cannot be done.  We can grab the resulting Account, Contact and Opportunity in the ‘After Trigger’ of the lead and do whatever we want to those objects there.  But our example of trying to do something to the lead before the ‘Convert’ occurs is basically not possible.  I was hoping the Before Trigger could help us out, but the actual convert action is causing the update to the Lead so that also does not help.  Another example is if you have ‘Person-Accounts’ enabled.  If this is true then the company field is no longer required. But maybe if the lead has a certain record type, then you want to make sure the company field gets filled out so that a Business account instead of a Person Account is created.  When Person Accounts are enabled the Company field is not longer required and a lead converts to a Person Account if the Company is not filled out.

What should we do?

To make these types of requirements work we have to go back to a standard pattern:
1) A custom button calls a Visualforce page.  We could call the new button ‘Convert Special’
2) The ID of the Lead is passed to the Apex Class and the lead is converted using the Database.LeadConvert object
3) The Visualforce page directs onto the resulting Account, Contact or Opportunity depending on your requirements.

That last one is nice.  In the typical lead ‘Convert’ scenario you are always redirected onto the Contact object, but since we have a Visualforce page in place we can now direct to wherever we want.  You would probably want to remove the standard ‘Convert’ button from your page layouts too.

Another thing that can be nicely done in the Apex class is to default the records types of the Account, Contact and/or Opportunity depending on the values of the lead that was converted.  This can really help the user to save time so that the resulting objects are setup automatically with the correct data.

The last thing I learned while working with these conversion requirements is that Notes and Attachments cannot be just transferred to another Account or Contact without writing a loop to do so which will create new objects.  The reason for this is that the parentID on the Note and Attachment records cannot be updated.  It is only though creating new records and then deleting the old ones that this is possible.  I had to work through this because it was a requirement in some cases to delete the resulting Contact object and then copy all of the Notes and Attachments from the Contact up to the Account.

Please let me know if Sundog can help you with any Lead Scoring or Lead Conversion activities in your Salesforce processes!

Posted in Technology | Tagged , , | Leave a comment

COMMUNICATE FROM A COMPONENT TO THE PAGE – VISUALFORCE

Visualforce has many different layers that make it easy to organize our pages and our code.  The visual portion of the page which includes the CSS, HTML and Apex Visualforce tags, which help to create more HTML, are kept in a Visuaforce Page.  This Visualforce Page then can point to an Apex Class, which should contain our business logic, by using the controller attribute.  The page would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
<apex:page controller="blogController" showheader="true" sidebar="true">
   <apex:form>
      <apex:commandbutton value="Add 1" action="{!add1}" rerender="myIntPanel"></apex:commandbutton>
      <apex:commandbutton value="Subtract 1" action="{!subtract1}" rerender="myIntPanel"></apex:commandbutton>
      <apex:outputpanel id="myIntPanel">
        <apex:outputtext value="{!intVale}"></apex:outputtext>
      </apex:outputpanel>
   </apex:form>
</apex:page>

Here is our Apex Class that would contain the business logic related to that Visualforce Page:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public with sharing class blogController{
   public integer intValue{get;set;}
   public blogController(){
      intValue = 0;
   }
   public pageReference add1(){
      intValue += 1;
      return null;  
   }
   public pageReference substract1(){
      intValue -=1;
      return null;
   }
}

This page and controller are pretty simple.  They allow you to manipulate the intValue integer on the controller.

But what if you had a component on that page and that component wanted you to add 5 or subtract 5 from the intValue?  How would it talk to the controller for the page?  It seems difficult because the page and the component will have different controllers.  But we can make this call by following a couple of steps to make the communication possible.  First, let’s add the add5() and subtract5() methods to our existing controller so it can be called.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public with sharing class blogController{
   public integer intValue{get;set;}
   public blogController(){
      intValue = 0;
   }
   public pageReference add1(){
      intValue += 1;
      return null;  
   }
   public pageReference substract1(){
      intValue -=1;
      return null;
   }
   public pageReference add5(){
      intValue += 5;
      return null;  
   }
   public pageReference substract5(){
      intValue -=5;
      return null;
   }
}

Then on our page we could add these actionFunction items:

1
2
<apex:actionfunction action="{!add5}" name="add5" rerender="myIntPanel"></apex:actionfunction> 
<apex:actionfunction action="{!subtract5}" name="subtract5" rerender="myIntPanel"></apex:actionfunction> 

The actionFunction exposes a Javascript function that can be called from anywhere on the page, including from within components on that page.

This Javascript function then exposes a hook for our component to make a call back to the page itself.  Of course this is setting up a dependency between the component and the page on which it resides, but maybe that would be the correct situation in some use cases.

Here could be our component.  Notice how the buttons are calling the actionFunction items on the Visualforce page.  Let’s assume for later that we save our component file as Add5Subtract5.component.

1
2
3
4
<apex:component controller="blogComponentCtl">
     <apex:commandbutton value="Add 5" onclick="add5();return false;">
     <apex:commandbutton value="Subtract 5" onclick="subtract5();return false;">
</apex:commandbutton></apex:commandbutton></apex:component>

We do not even need to write out any code in the blogComponentCtl class, which is the controller for the component, because that class is not really helping us with this requirement.

We finally need to add the component to our page with the ‘c:’ notation.

1
2
3
4
5
6
7
8
9
10
11
12
13
<apex:page controller="blogController" showheader="true" sidebar="true">
   <apex:form>
      <c:add5subtract5></c:add5subtract5>
      <apex:commandbutton value="Add 1" action="{!add1}" rerender="myIntPanel"></apex:commandbutton>
      <apex:commandbutton value="Subtract 1" action="{!subtract1}" rerender="myIntPanel"></apex:commandbutton>
      <apex:outputpanel id="myIntPanel">
        <apex:outputtext value="{!intVale}"></apex:outputtext>
      </apex:outputpanel>
   </apex:form>
</apex:page>

Now everything should flow through.  The buttons in the component will call the actionFunction on the page, which will then call the desired method on the page’s controller.

There seems like a lot of steps there, but they really fit together pretty nicely.

Happy Visualforcing!

 

Posted in Technology | Tagged , , , | Leave a comment