Concepts or coding lessons of Salesforce that you can implement easily

Easiest way to Display Asset Library File in Salesforce Community

This blog explain how to access asset library file uploaded from Salesforce CRM into Salesforce lightning Community.

I have created Salesforce Lightning Community with Standard "Customer Account Portal" community template.

Requirement, I have HTML editor (drag and drop) where i want to display asset file which is uploaded into Salesforce CRM.

for example, I have uploaded IconOne.jpg into Asset Library.
below code snippets display this uploaded IconOneImage into Salesforce community.

<img src="{!contentAsset.IconOne.1}"  alt="IconOne"/>

In above code, digit "1" is added after IconOne which indicates version of uploaded image.

Thats It.

Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.

Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 

Latest Salesforce Interview Questions and Answers:

7 Easy Steps to Call Connected App From Salesforce

In this blog, I am going to talk about How we can call Connected App from Salesforce itself and invoke one of the REST web service after successful authentication.

1. Create Connected App: Populated below data into Connected App setup page:

Few things which are important in this step
    • Set Callback URL to your custom Visualforce page link(Step 3).
    • Selected OAuth Scopes : All Available OAuth Scopes
Connected App Configuration


2. Copy below highlighted Consumer Key and Consumer Secret:




3. Create Visualforce Page : oAuth_Test

<apex:page controller="oAuthTokenController" action="{!startOAuth_step_2}">
  <apex:form >
  <apex:commandButton action="{!startOAuth}" value="Start oAuth Code" rerender="msgs"/>
  <apex:commandButton action="{!getNewAccessToken}" value="Get New Access Token" rerender="msgs"/>
  <apex:commandButton action="{!methodGet}" value="Call Webservice" rerender="msgs"/>
  </apex:form>
  <apex:outPutPanel id="msgs">
      Authorize code => {!authCode}<br/>
      Access Token => {!accToken}<br/>
      Refresh Token => {!refToken}<br/>
      Instance URL => {!insURL}<br/><br/><br/><br/>
      Web Service Response URL => {!wsResponce}<br/>
  </apex:outPutPanel>
</apex:page>

4. Create Apex class : oAuthTokenController

public class oAuthTokenController{
private auth_response objAutoRes;
public String consumerKey = 'YOUR CONSUMER KEY';
   public String consumerSecret = 'YOUR CONSUMER SECRET';

public String authCode {get; set;}
public String accToken {get; set;}
public String refToken {get; set;}
public String insURL {get; set;}
public String wsResponce {get; set;}

// BELOW METHOD FETH AUTHRIZATION CODE
public pagereference startOAuth(){
String auth_url = 'https://test.salesforce.com/services/oauth2/authorize';
String params = 
'?response_type=code' +
'&client_id=' + encodingUtil.urlencode(consumerKey,'UTF-8') +
'&redirect_uri=https://test.salesforce.com/apex/oAuth_Test' +
'&prompt=consent' +
'&scope=' + encodingUtil.URLEncode('full refresh_token','UTF-8') +
'&state=step2';
pageReference pr = New PageReference(auth_url + params);
return pr;
}

// GET ACCESS TOKEN AND REFRESH TOKEN
public pagereference startOAuth_step_2(){
System.debug('state=> '+apexPages.currentPage().getParameters().get('state'));
if(apexPages.currentPage().getParameters().get('state') != 'step2')
return null;

authCode = apexPages.currentPage().getParameters().get('code');

HttpRequest req = new HttpRequest();
Http http = new Http();
String auth_url = 'https://test.salesforce.com/services/oauth2/token';
String params = 
'?code=' + apexPages.currentPage().getParameters().get('code') +
'&grant_type=authorization_code' +
'&client_id=' + encodingUtil.urlencode(consumerKey,'UTF-8') +
'&client_secret=' + consumerSecret +
'&redirect_uri=https://test.salesforce.com/apex/oAuth_Test';
req.setMethod('POST');
req.setEndpoint(auth_url + params);
HTTPResponse resp = http.send(req);
objAutoRes = (auth_response)json.deserialize(resp.getBody(),auth_response.class);

accToken = objAutoRes.access_token;
refToken = objAutoRes.refresh_token;
insURL = objAutoRes.instance_url;

return null;
}

// GET NEW ACCESS TOKEN AFTER EXPIRY OF OLD ACCESS TOKEN
public void getNewAccessToken(){
// First revoke current Access token before requesting new token
String URL = objAutoRes.instance_url;
String urlRevoke = '/services/oauth2/revoke?token=';
String tokenEncode = EncodingUtil.URLENCODE(objAutoRes.access_token,'UTF-8');
URL += urlRevoke += tokenEncode;

HttpRequest req = new HttpRequest();
req.setEndpoint(URL);
req.setHeader('Content-Type','application/x-www-form-urlencoded');
req.setMethod('GET');
 
Http http = new Http();
HttpResponse res = http.send(req);
system.debug('CR=response= '+res);

// Now request for new access token using refresh token

HttpRequest refreshRequest = new HttpRequest();
Http refreshHttp = new Http();
String auth_url = 'https://test.salesforce.com/services/oauth2/token';
String params = 
'?grant_type=refresh_token' +
'&client_id=' + encodingUtil.urlencode(consumerKey,'UTF-8') +
'&client_secret=' + consumerSecret +
'&refresh_token=' + encodingUtil.URLEncode(objAutoRes.refresh_token,'UTF-8');
refreshRequest.setMethod('POST');
refreshRequest.setEndpoint(auth_url + params);
HTTPResponse refreshResp = refreshHttp.send(refreshRequest);

objAutoRes= (auth_response)json.deserialize(refreshResp.getBody(),auth_response.class);

accToken = objAutoRes.access_token;
insURL = objAutoRes.instance_url;
}

// Retrieve the Accounts from the Salesforce org.
    public void methodGet(){       
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
       
        req.setEndpoint(objAutoRes.instance_url+'/services/apexrest/WebServiceTestingTool');
        req.setHeader('Authorization', 'OAuth '+objAutoRes.access_token);
        req.setHeader('Content-Type', 'application/json');
        Http http = new Http();
        HTTPResponse res = http.send(req);
       
        System.debug('***methodGet Response***** ' + res.getBody());
wsResponce = res.getBody();
    }
private class auth_response{
public string refresh_token;
public string access_token;
public string instance_url;
}
}

5: Create Apex class which acts as REST webservice namely TestRestWebservice and copy below code:

@RestResource(urlMapping='/WebServiceTestingTool/*')
global class TestRestWebservice {
    @httpGet                     
    global static void WSPolicyData (){
        RestRequest req = RestContext.request;
       
        try{
            List<Account> result = [SELECT Name FROM Account LIMIT 1];
            RestContext.response.responseBody = Blob.valueOf(JSON.serializePretty(result));
        }
        catch(Exception ex){
            System.debug(ex.getMessage());
        }
    }
}

6: Create TWO remote site setting like below:

7: Go to oAuth_Test Visualforce page we have created in step 3 and click on button.

    Click on Start oAuth Code button and authorize the App. After successful authorization you will get below details:



Thats It.

Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 

Latest Salesforce Interview Questions and Answers:

Previous And Next Email Message Buttons in Lightning


If you are using Service cloud and have Email-to-Case functionality implemented, then this blog is useful for you.

In Lightning, Salesforce didn't provide standard functionality of Previous and Next actions on Email Message Objects which exist in Salesforce Classic version.

Lets take scenario, there is complaint case from user which is raised 10 days back and your servicing Team leader want to check all email history of that case.

This is common scenario happens in every organizations. If Team Leader is in Classic he can check all email history using Previous and Next buttons shown below.




But what about Lightning ???
There is no such standard functionality in Lightning, MUCH NEEDED !!

I have implemented workaround for this using Customization's.
Copy and paste below codes.

1. Create Apex Class: EmailMessageActions 

public class EmailMessageActions {
    public Id prevId {get;set;}
    public Id nextId {get;set;}
    public Id caseId {get;set;}
    public Boolean isLex {get;set;}
    public String prevURL {get;set;}
    public String nextURL {get;set;}
    public String emailMsgListURL {get;set;}
    public EmailMessage eMsg;
    public String statusMsg {get;set;}
    
    public EmailMessageActions(ApexPages.StandardController stdController) {        
        this.eMsg = (EmailMessage)stdController.getRecord();
        statusMsg = null;
        getPreviousNextEMsgIds();
    }
    
    public PageReference previousMsg(){
        //statusMsg = 'Loading...';
        System.debug('In previousMsg');
        if(prevId!=null){
            PageReference page = new PageReference(prevURL);
            page.setRedirect(true);
            return page;
        }
        else
            statusMsg = 'No More Previous Emails.';
        return null;
    }
    public PageReference nextMsg(){
        System.debug('In nextMsg');
        if(nextId!=null){
            PageReference page = new PageReference(nextURL);
            page.setRedirect(true);
            return page;
        }
        else
            statusMsg = 'No More Next Emails.';
        return null;
    }
    public PageReference emailMsgList(){
        System.debug('In emailMsgList');
        PageReference page = new PageReference(emailMsgListURL);
        page.setRedirect(true);
        return page;
    }
    public void getPreviousNextEMsgIds() {
        System.debug('eMsg--'+eMsg.Id);
        for(EmailMessage obj: [SELECT ParentId FROM EmailMessage WHERE Id =:eMsg.Id])
            caseId = obj.ParentId;
        System.debug('caseId--'+caseId);
        List<Id> lstId = new List<Id>();
        for(EmailMessage obj: [SELECT Id FROM EmailMessage WHERE ParentId =:caseId ORDER BY MessageDate ASC])
            lstId.add(obj.Id);
        System.debug('lstId--'+lstId);
        Integer result = lstId.indexOf(String.valueOf(eMsg.Id));
        System.debug('result--'+result);
        if(result > 0){
            prevId = lstId.get(result-1);
            if(result < lstId.size()-1)
                nextId = lstId.get(result+1);
        }
        else if(result == 0 && lstId.size() > 1)
            nextId = lstId.get(result+1);
        
        String uiThemeDisplayed = UserInfo.getUiThemeDisplayed();
        if(uiThemeDisplayed.equalsIgnoreCase('Theme4d'))
            isLex = true;
        else 
            isLex = false;
        System.debug('isLex--'+isLex);
        String sfdcBaseURL = URL.getSalesforceBaseUrl().toExternalForm();
        if(isLex){
            if(prevId!=null)
                prevURL = sfdcBaseURL+'/lightning/r/EmailMessage/'+prevId+'/view';
            if(nextId!=null)
                nextURL = sfdcBaseURL+'/lightning/r/EmailMessage/'+nextId+'/view';
            emailMsgListURL = sfdcBaseURL+'/lightning/r/'+caseId+'/related/EmailMessages/view';
        }
        else{
            if(prevId!=null)
                prevURL = sfdcBaseURL+'/'+prevId;
            if(nextId!=null)
                nextURL = sfdcBaseURL+'/'+nextId;
            emailMsgListURL = sfdcBaseURL+'/ui/email/EmailMessageListPage?id='+caseId;
        }
        System.debug('prevURL--'+prevURL);
    }
}

2. Create VisualForce Pages: PreviousEmailMessage

 <apex:page standardController="EmailMessage" extensions="EmailMessageActions" action="{!previousMsg}" showHeader="false" showQuickActionVfHeader="false">
<h1 style="font-size:1.125rem;">{!statusMsg}</h1>
<base target="_parent" />
</apex:page>

3. Create VisualForce Pages: NextEmailMessage

 <apex:page standardController="EmailMessage" extensions="EmailMessageActions" action="{!nextMsg}" showHeader="false" showQuickActionVfHeader="false">
<h1 style="font-size:1.125rem;">{!statusMsg}</h1>
<base target="_parent" />
</apex:page>

4. Create VisualForce Pages: EmailMessageList

 <apex:page standardController="EmailMessage" extensions="EmailMessageActions" action="{!emailMsgList}" showHeader="false" showQuickActionVfHeader="false">
<base target="_parent" />
</apex:page>

5. Create 3 Action Buttons for Email Message Object like Below


6. Give Profile Permissions to above Apex Class and VisualForce Pages.

7. Add these actions into Email Message Lightning Page Layout.


Thats It.

Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 

Latest Salesforce Interview Questions and Answers: