Saturday, February 18, 2017

Retrieve Salesforce custom label dynamically in Apex

Ever wonder if it is possible to retrieve custom labels dynamically but not sure whether it is possible? Well, the answer is yes. You can retrieve custom labels dynamically.

Here is how you can achieve it. You just need to integrate the following code in  your apex class.

Hope you like it. Cheers!
public static String getLabelString(String labelName ){ Component.Apex.OutputText output = new Component.Apex.OutputText(); output.expressions.value = '{!$Label.' + labelName + '}'; return String.valueOf(output.value); }

Tuesday, February 14, 2017

Using Salesforce standard modal in a Detail page button - Part 1

Tired of having to use window.open in a detail page button to display a popup? Or using JavaScript libraries to display a modal?
Well, there is a more simple way to display a popup and this without embedding any JavaScript library in the code.

This can be achieved by using Salesforce standard modal and by tweaking the code, many things can be achieved.

To get started, Create a Custom button on the object you want the modal to be used.
Set the properties to:
Display Type: Detail Page Button
Behavior: Execute JavaScript
Content Source: OnClick JavaScript

custom button salesforce

In the JavaScript code editor, add the following code and change the variables inside it accordingly to your specification.

Here is the final result:

Check out part 2. We shall discuss how to integrate Visualforce pages inside the modal.

Cheers! :)
(function() { var width = 700; var height = 200; var title = "Dialog title here"; var box = new SimpleDialog("salesforce" + Math.random(), true); box.setTitle(title); box.displayX = true; box.isMovable = false; box.createDialog(); box.setWidth(width); // set your html content here box.setContentInnerHTML( "<h2>Your html content here</h2>" ); //set the height of the modal box.dialog.children[1].style.height = height + 'px'; box.show(); //if displayX is set to true, then override standard close event by this code box.dialog.getElementsByClassName('dialogClose')[0].onclick = function() { box.hide(); // you can add code to reload the page or redirect to another page }; //optional : add this to close the modal onclick of the overlay background box.background.addEventListener('click', function() { box.hide(); }); })();

Using Salesforce standard modal in a Detail page button - Part 2

As illustrated in Part 1, we looked at opening the modal which come with Salesforce and changing its content.

But most of the time, you want the content in the JavaScript detail button to be dynamic. So instead of writing a lot of JavaScript code and encoding the HTML content into a string to then pass it to the setContentInnerHTML function, we could display a Visualforce page.

You just need to modify it as below and change the source (src attribute).
box.setContentInnerHTML(
  '<iframe src="/apex/modaldemo" style="border:none;" width="100%" height="'+ (height - 30)+'px" />'
);

We have now added a Visualforce page, which is kind of awesome. But what if we want to some processing and at the end close the modal from within the Visualforce page?

Well, this is not possible since you don't have access to the modal instance in the Visualforce page.
Fortunately we do have an alternative way which is the use of postMessage.

How does it work? 
First we need to the Visualforce page to send the message once the action is done. Which can be a click on button, a progress bar reaching 100%, an action function which has completed or many other scenarios. 

You just need to execute the following JavaScript code:
window.parent.postMessage('close', '*');

Now we need to capture this message from the JavaScript on the button and then close the modal. Here is how we do it. 
window.addEventListener('message', function(event){
  if (event.data === 'close'){
    box.hide();
  }
});

Below is the full implementation: 


Hope you like it. :)

Sunday, February 12, 2017

Introduction to Apex

Each year we are having struggle training fresh graduate from the University into learning the basic of Salesforce Apex programming language. They mixed up the syntax with what Java would look like.
So we came up with a list of things that would speed up the process of training.

Here's a list of the commonly used syntax in Apex and restrictions:

Hope this tutorial is useful to you.

Cheers!

# Intro to apex

## Basic operation
``` java
//variable declaration
Integer val = 0;
string str = 'Super test'; // apex allow only single quote for string variable
boolean isDeleted = true;

/*Concatenate string*/
string firstname = 'John';
string lastname = 'Doe';
string name = firstname + ' ' +  lastname;
```

## Debug Apex code
``` java
string name = 'Super test';
system.debug('### '+name); // ### Super test

```

## Collection
A collection in apex is either a "List", "Set" or a "Map"

``` java
/**
* List
*/
//Populating method 1
list<string> carList = new list<string>();  //initializing an empty list
/*Populating the list*/
carList.add('Honda');
carList.add('Toyota');
carList.add('Mazda');

//Populating method 2
list<string> carList = new list<string>{'BMW', 'Mercedes', 'Audi'};

/**
* Set
*/
set<string> referenceSet = new set<string>();
referenceSet.add('test');
//or
set<string> referenceSet = new set<string>{'test'};

/**
* Map
* A map consists of a key and value. The key should always be a primitive type (string, integer, id, ...).
*/
map<string, string> countryCodeMap = new map<string, string>(); //initiliazing an empty map
//Populating a map
countryCodeMap.put('Mauritius', 'MU');
countryCodeMap.put('France', 'FR');
//or
map<string, string> countryCodeMap = new map<string, string>{'Mauritius'=>'MU', 'France'=>'FR'};

//accessing a value for a specific key in the map
string franceCode = countryCodeMap.get('France'); //returns FR
```

## sObject
Any standard and custom object in Salesforce is represented as an sObject in Apex.

Example

| Object type | Name     | Api name (as represented in apex) |
| ----------- | ---------- | ----------------------------------- |
| Standard | Account  | Account |
| Standard | Contact | Contact |
| Custom | Car | Car__c |
| Custom | Job | Job__c |

``` java
//Create a new instance of an sObject
Contact con1 = new Contact(); //initializing an instance of a contact
con1.Firstname = 'Jane';
con1.Lastname = 'Doe';

// or
Contact con1 = new Contact(Firstname='Jane', Lastname='Doe');

/*custom object*/
Job__c job = new Job__c();

//creating an instance of an existing record
Account salesFr = new Account(Id='0012400000YwpHM'); //you just need to instantiate with the field "Id"

```

### Note
A lookup or master-detail relationship fields in apex is represented by an Id.

## DML
DML operations consists of:
- insert
- update
- upsert
- delete
- undelete
- merge

### Insert
```java
Account telecom = new Account(Name='Telecom');
insert telecom;
```
### Update
```java
telecom.Name = 'Telecom - Head office';
update telecom;
```
### Upsert
It does an insert if record not found else update if found.
Generally use with an ExternalId (a flag on a field to make it an index)
```java
//account does not exist
Account sbm = new Account(Name='SBM');
upsert sbm; // will create an account with Name = SBM
//account exist
Account sbm = new Account(Id='0012400000YwpHM', Name='SBM - Closed');
upsert sbm; // will update with Name = 'SBM - Closed'

//update a contact based on its external id (here Email is defined as external id)
Contact con1 = new Contact(Email='plop@test.com', Lastname='Plop');
upsert con1 Contact.Email;
```
### Delete and Undelete
Can only delete instance which contains an Id.
```java
Account sbm = new Account(Id='0012400000YwpHM');
delete sbm;

undelete sbm;
```

## SOQL queries
SOQL query will always return the following:
- an sobject
- a list of sobjects
- a list of objects

### Basic query
```java
//Returning only one record
Contact jane = [SELECT Id, Firstname, Lastname FROM Contact WHERE Id = '0032400000GRVvY'];

//returning a list of record
list<Account> accountList = [SELECT Id, Name FROM Account];
```
### Advanced query
```java
// returning a list of contact with their account name
list<Contact> contactList = [SELECT Id,
                                    Firstname,
                                    Lastname,
                                    Account.Name
                            FROM Contact
                            WHERE AccountId != null];

// returning list of account with their children(contacts)
list<Account> accountList = [SELECT Id, Name,
                                (SELECT Id, Firstname, Lastname from Contacts)
                            FROM Account];
```
Notice that the child relationship is in plural.
If a custom object was used here
- parent relationship: objectName**__r**
- child relationship: objectName**s__r**


## Loops
``` java
for(integer i = 0; i < size; i++){
  // code here
}

/*Example*/
list<string> firstnames = new list<string>{'John', 'Jane'};
list<string> lastnames = new list<string>{'Smith', 'Doe'};
list<string> names= new list<string>();
for(integer i = 0; i < firstnames.size(); i++){
  string name = firstnames[i] + ' ' + lastnames[i];
  names.add(name);
}

//or
for(type variable: list<type>){
  //do any operation with variable
}

/*Examples*/
integer total = 0;
list<Account> accountList = [SELECT id, NumberOfEmployees FROM Account];
for(Account acc: accountList){
  if (acc.NumberOfEmployees != null){
    total = total + acc.NumberOfEmployees;
  }
}

```

## Classes and Methods
``` java
public class Employee {
  public string name;
  public integer age;
  public datetime arrivedAt;
  public Employee(){
  }
  public void checkIn(){
    //void just do the action
    arrivedAt = System.now();
  }
  public boolean shouldRetire(){
    integer diff = 65 - age;
    if (diff <= 0){
      return true;
    }
    return false;
  }
  public static integer numEmployees(){
    list<Employee__c> employees = [select id from Employee__c];
    return employees.size();
  }
}

//Creating an instance of employee
Employee emp = new Employee();
emp.name = 'john';
emp.age = 30;
//call checkIn method for the employee
emp.checkIn(); // void method do the action only
retired = emp.shouldRetire(); // non void method should return a value

//Calling static methods
Employee.numEmployees();
```

Saturday, February 11, 2017

Nice css spinner for Visualforce pages

Did it ever happen that you have design a nice looking Visualforce page and had to insert a loading icon but didn't want to use the one provided by Salesforce (see image below)?

Well it happened to me a lot of time that I needed to find a reusable piece of code for a loading/spinner icon. Doing some research I found a that this guy, Tobias Ahlin, has come up with a SpinKit (https://github.com/tobiasahlin/SpinKit). So I decided to make a reusable component for having different kind of spinner with customize colors.

It is pretty easy to use, just need to copy the component on your Salesforce environment and execute some JavaScript whenever you want to toggle on and off the spinner/loading.

Source code can be found here: https://github.com/kevanmoothien/sfdc-spinner



The result should look something like that:

A live demo of all the spinners is available at: http://tobiasahlin.com/spinkit/

Hope you like this tutorial.

If you have any suggestions on how to improve this component, I will be glad to hear them.

Cheers!!

Installation

Click on the link below and add the codes in a visualforce component name "spinner" or any other name that sound best for you

Basic usage

Include the Visualforce component on the Visualforce page you want to use the spinner/loading like in the code below.
<apex:page>
  <c:spinner />
</apex:page>
Displaying the spinner
To display the spinner, a JavaScript code must be executed. Here are the code
km_spin(true); // to show the spinner
km_spin(false); // to hide the spinner

Advanced usage

Customizing the spinner
You can further customize the Spinner by adding some attributes such as in the code below:
<apex:page>
    <c:spinner spinner_name="wave"  spinner_color="red" />
</apex:page>
Possible value for "spinner_name" are:
  • rotating-plane
  • wave
  • wandering-cubes
  • spinner-pulse
  • double-bounce
  • chasing-dots
  • three-bounce
  • circle
  • cube-grid
  • fading-circle
  • folding-cube
Value for "spinner_color" is a hex or html color name


Thursday, February 9, 2017

Does a Lightning Component know if it is in a Community or a standard Lightning Salesforce page?

Title says it all. Does a Lightning Component know if it is in a Community or a standard Lightning Salesforce page?
I have a component that implements both the interface for Community as Standard Lightning.
Some people suggest to add an attribute and set it in the Lightning App Builder or Community Builder so as to distinguish in which kind of environment we are.

It is quite annoying for the System Administrator to configure the behavior of the component each time it is needed.

But what if this can be achieved automatically by only a few lines of code?

Here is how I did it:

Your component must first extends a controller.

I Hope that this post will be helpful to you. Cheers!!
Lightning component .cmp aura:component implements="force:hasRecordId, force:appHostable, flexipage:availableForAllPageTypes, forceCommunity:availableForAllPageTypes" controller="CustomController"> aura:handler name="init" value="{!this}" action="{!c.init}"/> /aura:component Apex controller .cls public with sharing class CustomController { @AuraEnabled public static boolean isCommunity(){ Id siteId = Site.getSiteId(); if (siteId != null) { return true; } return false; } } Lightning component controller .js ({ init : function(component, event, helper) { var action = component.get("c.isCommunity"); action.setCallback(this, function(response) { var isCommunity = response.getReturnValue(); // do any operation needed here }); $A.enqueueAction(action); } })