Tech blog to share information.

June 16, 2018

Lightning Console Apps - 'Lightning Component Tab' Labels Display as “Loading…”

June 16, 2018 Posted by tj cool , , No comments

Lightning Console Apps


Lightning console apps help to view multiple records and their related records on the same screen, and quickly work through records from a list using the split view. This Saves lots of time. Creating custom tab in the console is also possible. But there is weird behavior with custom tabs.

If you are working on Lightning console and using the Lightning component as a custom tab in Service Console, the content loads fine but tab label stays on "Loading..." forever.

If you have faced this issue, here's the quick workaround.

1. Put this line in your component.
 //in markup

 <lightning:workspaceAPI aura:id="workspace"/>

2. Add a render event handler to your component's markup.
<aura:handler action="{!c.onRender}" name="render" value="{!this}"></aura:handler>

3. Add below code in action ("onRender") or you can also put the code in init handler
        
        var workspaceAPI = component.find("workspace");
        workspaceAPI.getFocusedTabInfo().then(function(response) {
         var focusedTabId = response.tabId;
         workspaceAPI.setTabLabel({
          tabId: focusedTabId,
          label: "Edit Contact" //set label you want to set
         });
         workspaceAPI.setTabIcon({
          tabId: focusedTabId,
          icon: "utility:add_contact", //set iconyou want to set
          iconAlt: "Edit Contact" //set label tooltip you want to set
         });
        })


May 18, 2018

Salesforce - Feature Developer asking from Years, Switch Statement

May 18, 2018 Posted by tj cool , , , No comments

Switch Statement - Feature Developer asking for Years


Salesforce Dev community has been asking for switch statement for many years( 4+ years) and finally, Salesforce has introduced "switch" in Summer 18. I don't know why Salesforce has taken so much time to introduce a common statement in programming.

Switch

We all know, Switch statement allow us to change the control flow of program execution via a multiway branch. In a Recent release (Summer-18) Salesforce has finally introduced "switch" statement. Flavor of "switch" that Salesforce has introduced is bit different. What we have seen (at least me) "switch - case", whereas Salesforce has come with "switch-when".
When I used it, I got a feeling of writing "if-else if" 😁 .

This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.

Check out the below syntax of a switch-

switch on expression {
    when value1 {  // when block 1
        // code block 1
    } 
    when value2,value3 {  // when block 2
        // code block 2
    }
    when value4 {  // when block 3
        // code block 3
    }
    when else {    // default block, optional
        // code block 4
    }
}

Here when a value can be a single value, multiple values, or sObject types.The switch statement evaluates the expression, executes the code block but if no value matches, then when else code block is executed.

Switch statement expressions support following types.

  • Integer
  • Long
  • sObject
  • String
  • Enum

When values can be of following forms.

  • when literal {} (a when block can have multiple, comma-separated literal clauses)
  • when SObjectType identifier {}
  • when enum_value {}

Some of the Example of Switch

Single Value Example: 

switch on datatype {
   when 'string' {
       string.valueof(variablename);
   }
   when 'decimal' {
       Decimal.valueof(variablename);
   }
   when else {
       System.debug('default');
   }
}

Multiple Values Examples: 

switch on i {
   when 2, 3, 4 {
       System.debug('when block 2 and 3 and 4');
   }
   when 5, 6 {
       System.debug('when block 5 and 6');
   }
   when 7 {
       System.debug('when block 7');
   }
   when else {
       System.debug('default');
   }
}

Working with sObjects : 

switch on sobject {
   when Account a {
       System.debug('account ' + a);
   }
   when Contact c {
       System.debug('contact ' + c);
   }
   when null {
       System.debug('null');
   }
   when else {
       System.debug('default');
   }
}

Working With ENUM-

switch on userType {
   when admin {
       System.debug('admin');
   }
   when guest {
       System.debug('guest');
   }
   when else {
       System.debug('none of the above');
   }
}

References-

Thanks to @Rahul Agrawal for sharing.


Please do comment, like and Subscribe -

May 17, 2018

Salesforce : Use Single Inbound Email Service to Process Various Emails .

May 17, 2018 Posted by tj cool , , No comments

- Use Single Inbound Email Service to Process Various Emails -

You can use Apex to receive and process email and attachments. The email is received by the Apex email service and processed by Apex classes that utilize the InboundEmail object.

For example - You can create an email service that automatically creates contact records based on contact information in messages

In this post, we will be covering, use case where Salesforce will be receiving an email from different automated systems say Fax system or from Particular email alias.

Part I - Apex Code for Dynamically Processing Email -

We will be invoking class dynamically in this part. Below are the steps for same.

a) Create Interface 

global class IEmailProcessor {
    object Process(Messaging.inboundEmail email);
}

b) Implement Class IEmailProcessor 

global class FaxProcessor implements IEmailProcessor  {
  public object Process(Messaging.inboundEmail email){
 //All email processing logic will come over here like record creation
  }
}

Part II- Creating Apex Class for Email Service - 

1. Create Apex class and implement interface Messaging.InboundEmailHandler
2. Using "handleInboundEmail" method in that class, you can access an InboundEmail object to retrieve the contents, headers, and attachments of inbound email messages. "handleInboundEmail" has two parameters
   a) Inbound email: Represents an inbound email object and can say contains complete details about an email like attachments, message, sender details.
   b) InboundEnvelope: The InboundEnvelope object stores the envelope information associated with the inbound email, and has fields fromAddress and toAddress.

Snippet - 

global class EmailExample implements Messaging.InboundEmailHandler {
 
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
  
    // Create an InboundEmailResult object for returning the result of the  Apex Email Service
    Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
    try{    
       //Add the email plain text into the local variable 
       string sender=email.fromname;
       EmailProcessor__c apexClass= EmailProcessor__c.getValues(sender);
       if(apexClass.isActive__c){
          //Create type
          Type type = Type.forName(apexClass.Apex_Class__c);

          //using new instance we create ew instance of class.  
          object instance = type.newInstance();
          
          //typecast
          IEmailProcessor interfaceInstance = (IEmailProcessor)instance;
          
          //invoke method
          object result= interfaceInstance.Process(email);
       }else{
         result.success = false;
       }
   }  
   // If an exception occurs when the query accesses 
   catch (QueryException e) {
       System.debug('Query Issue: ' + e);
   }
   
   // Set the result to true. No need to send an email back to the user with an error message 
    result.success = true;
   
   // Return the result for the Apex Email Service
   return result;
  }
}

Part III - Setting Up Email Service in Salesforce - 

Step1 -  Click Your Name > Setup > Develop > Email Services

Step2 & Step3 -


In my case apex, the class value would be: EmailExample 

Part IV - Create Custom Setting for Email and Apex class mapping. 

Below is a snapshot of my custom setting and field.



Populate custom settings with apex class and alias email address. Now when Salesforce will receive an email your class will get invoked and checks if the email is coming from configured service or not and if it so the appropriate class will get invoked.


Hope this Helpfull. Please Comment and Subscribe


May 10, 2018

Introduction - Client-side Template

May 10, 2018 Posted by tj cool , , , , No comments

In the world, where we have so many front-end frameworks around us, for some people this post is bit outdated. But, I thought sharing information is always helpful. 

Flashback……

We all know, when a web page is loaded, the browser creates a Document Object Model of the page. 
The HTML DOM model is constructed as a tree of Objects. With the object model, JavaScript gets all the power it needs to create dynamic HTML. And we all have created dynamic elements using javascript (at least I have done it :) )



Dynamic Element Creation - The approach we follow usually.

When developing modern HTML applications, we often write a lot of HTML fragments programmatically. We concatenate HTML tags and dynamic data and insert the resulting UI markup into the DOM.

Below are the random code example of this approach

 https://jsfiddle.net/tjcool/5qjLpo6t/

Code to Create or Add dynamic Content on the page : 

Javascript : 


Jquery - Code to add user messages in the container. 



And the problem starts…

For simple Dom manipulation, we write similar snippets shown in above previous examples.

Day by day as requirement gets complicated we start facing issues, issues like managing code, scripting performance issues, user experience, cross-browser compatibility. We end up writing code of thousand lines with a lot of dom manipulation.
It makes your application very tightly coupled and harder to maintain.
So, when we should avoid client-side Dom manipulation. So, based on my previous experiences and references from forums following are some of the use cases.
  • Complex projects which involve large amounts of client-side HTML manipulation with JavaScript.
  • When client expects good UX.
  • When you need to support mobile device as well.


Note: Use of jQuery clone, append method heavily as a clone and append methods degrade application performance if involved in large DOM manipulation. 

What is Template - First Impression.

“A document that contains parameters, identified by some special syntax, that are replaced by actual arguments by the template processing system.”

Quick Example -


When & Why would you use It 

In today’s world of dynamic applications, the client frequently wants moreover like plug and play user interface (UI) or can say dynamic UI and of course styling. This can be done by fetching an HTML fragment from the server that can be readily inserted into the document. Also, as a  developer, you want to have full control over your UI as well.

So let’s take a look at templating(client-side templating)

There are a number of HTML template solutions out there: 
  • Mustache.js
  • Handlebar.js 
  • Underscore.js 
Mustache.js is a popular choice because of its powerful syntax and fast rendering. In fact, Handlebar is a more advanced version of Mustache. There are also other front-end frameworks which use Mustache for UI rendering.



Please do comment, like and Subscribe

Client Side Templating - Getting Started with Mustache.js

May 10, 2018 Posted by tj cool , , No comments

Mustache.js is an open source logic-less template system. This doesn’t mean you can only have simple placeholders in a template, but the features are pretty limited to some intelligent tags (i.e. array iteration, conditional rendering, etc). Mustache provides templates and views as the base for creating dynamic templates. Views contain the data to be included in the templates as JSON. Templates contain the presentation HTML or data with the template tags for including view data.

Defining Template

An often seen solution is to put all the templates within "script" tags with an alternative type attribute, e.g. type=" text/template”. Some common MIME types are text/html , text/template and text/mustache. You can include as many templates in a document as you wish with different IDs. Heres the quick example -


Mustache Tags: {{}}

Tags are indicated by the double mustaches that surround them. {{username}} is a tag, as is {{#username}}. In examples, we refer to username as the tag's key. A mustache template can contain any number of mustache tags. Look at the below example.

Defining Variables :

The most basic mustache type is the variable. A {{name}} tag in a template and mustache engine will try to find the name key in the current context. If there is no name key in the current context, the parent contexts will be checked recursively. If the top context is reached and the name key is still not found, nothing will be rendered.

All variables are HTML escaped by default. If you want to return un-escaped HTML, use the triple mustache: {{{name}}}.

a) Binding JS variables - 

Let say we have a javascript variable and we want to bind it to a template. As your variable won’t have a key, you need to say “just bind the data”.  
When you want to bind js variables in mustache use dot ( . ) operator, this will get you the value.

JsFiddle

b) Binding with JSON Data - 

Consider you have written rest API which returns you a JSON object and you want to render the template. To do so check this fiddle. 

Sections - Polymorphism Behaviour

Sections render blocks of text one or more times, depending on the value of the key in the current context. A section begins with a pound and ends with a slash. The text between the two tags is referred to as that section's "block".
The behavior of the section is determined by the value of the key . 
Syntax-
{{#.}}
   binding
{{/.}}
Thumb Rule - 
  • If the key is of type boolean (true/false) - Mustache checks if the value is True and if so it will render.
  • If key is of type collection, then mustache will loop over collections and the block will be rendered one or more times.

a) Case 1 - False Values or Empty Lists

If the activeusers key does not exist, or exists and has a value of null, undefined, false, 0, or NaN, or is an empty string or an empty list, the block will not be rendered.
Data
{
  "activeusers": false
}
OR
{
  "activeusers":[]
}
OR
{
  "activeusers":null
}
Template
Shown.
{{#activeusers}}
Never shown!
{{/activeusers}}
Output
Shown

b) Case 2- Non-Empty Lists -

If the person key exists and is not null, undefined, or false, and is not an empty list the block will be rendered one or more times. When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way, we can loop over collections.
Data
{
  "activeusers": [
    { "name": "Moe" },
    { "name": "Larry" },
    { "name": "Curly" }
  ]
}
Template
{{#activeusers}}
{{name}}
{{/activeusers}}
Output
Moe
Larry
Curly

When looping over an array of strings, a . can be used to refer to the current item in the list.

Example

Data
 {"activeusers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]}
Template
{{#activeusers}}
* {{.}}
{{/activeusers}}
Output
* Athos
* Aramis
* Porthos
* D'Artagnan
JsFiddle

Conditional Statements - If-Else

An inverted section opens with {{^section}} instead of {{#section}}. The block of an inverted section is rendered only if the value of that section's tag is null, undefined, false, false or an empty list. Let's take a look at below example.

Data
{
  "UserloggedIn":false
  "username":null
}
Template
{{#UserloggedIn}}{{username}}{{/UserloggedIn}}
{{^UserloggedIn}}Welcome Guest({{/UserloggedIn}}
Output
Welcome Guest

JsFiddle


Mustache.js Documentation -


Please do Comment,Like and Subscribe