How to use the escapeSingleQuotes method?

Code Snippet :

public static String getRowById(String sobjName, Id id) {
    Map<String, Schema.SObjectField> objectFields =
        Schema.getGlobalDescribe().get(sObjName).getDescribe().fields.getMap();

    return 'SELECT ' + String.join( objectFields.keySet(), ', ')
           + ' FROM ' + sObjName
           + ' WHERE Id = \'' + String.escapeSingleQuotes(Id) + '\''
           + ' LIMIT 1';
}

Handling Inline images in Inbound Email Service Salesforce

Apex Code :

global class InboundEmailHandler implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        system.debug('==================');
        system.debug(string.join(email.ccAddresses,','));
        system.debug(email.fromAddress);
        system.debug(email.fromName);
        system.debug(email.inReplyTo);
        system.debug(email.messageId);
        system.debug(email.plainTextBody);
        system.debug(email.references);
        system.debug(email.replyTo);
        system.debug(email.subject);
        system.debug(string.join(email.toAddresses,','));
        //system.debug(email.headers);
        //system.debug(email.htmlBodyIsTruncated);
        //system.debug(string.join(email.textAttachments,','));
        //system.debug(string.join(email.headers,','));
        //system.debug(email.htmlBody);
        //system.debug(string.join(email.binaryAttachments,','));
        system.debug('==================');
       
        Lead lead = new Lead();
        lead.LastName =email.fromName;
        lead.Description = string.join(email.ccAddresses,',') +'\n'+ email.messageId +'\n'+ email.references +'\n'+ email.replyTo +'\n'+ email.htmlBodyIsTruncated +'\n'+ string.join(email.headers,',') +'\n'+ string.join(email.binaryAttachments,',');
        lead.recordtypeId='0120Y0000002qJe';
        lead.Email = email.fromAddress;
        lead.Company = 'N/A';
        lead.HTML_Body__c = email.htmlBody;
        insert lead;
        Map< String, Attachment > mapAttachments = new Map< String, Attachment >();
        for(Messaging.InboundEmail.BinaryAttachment bA : email.binaryAttachments) {
            System.debug('binary attachment :: '+email.binaryAttachments.size());
            System.debug('BA header size attachment :: '+bA.headers.size()+'---'+bA.headers);
            for(integer i = 0; i < bA.headers.size(); i++) {
                String headerValue = bA.headers[i].value;
                System.debug('headerValue  :: '+headerValue);
                if(headerValue.startsWith('ii') || headerValue.startsWith('<image')) {
                    headerValue = headerValue.replaceAll('<', '').replaceAll('>', '');
                    system.debug('final header value :: '+headerValue);
                    mapAttachments.put(headerValue, new Attachment(Name = bA.fileName, body = bA.body,ParentId = lead.Id, ContentType = bA.mimeTypeSubType));
                }
            }
        }
        //system.debug('mapAttachments :: '+mapAttachments);
        insert mapAttachments.values();
        //system.debug('Attachement List :: '+mapAttachments);
        for(String headerValue : mapAttachments.keySet()) {
            //system.debug('headerValue List :: '+headerValue);
            String refLink = '/servlet/servlet.FileDownload?file=' + mapAttachments.get(headerValue).Id;
            //system.debug('refLink  List :: '+refLink);
            lead.HTML_Body__c = lead.HTML_Body__c.replaceAll('cid:' + headerValue, refLink);
            //system.debug('replaceAll List :: '+lead.HTML_Body__c.replaceAll('cid:' + headerValue, refLink));
        }
        update lead;       
        return result;
    }
}

Screenshot :


Rollup Sumary in lookup relationship using triggers salesforce

Trigger Code :

trigger parentChildCount_Trg on Contact(after insert, after update, after delete, after undelete) {
    Map < Id, Account > conMapId = new Map < Id, Account > ();
    Set < Id > conSetIds = new Set < Id > ();
    for (Contact con: ((trigger.isAfter) && (trigger.isInsert || trigger.isUndelete || trigger.isUpdate)) ? trigger.new : trigger.old) {
        if (String.isNotBlank(con.AccountId)) {
            conSetIds.add(con.AccountId);
        }
    }
    conSetIds.remove(null);
    if (!conSetIds.isEmpty()) {
        for (Id acctId: conSetIds) {
            conMapId.put(acctId, new Account(Id = acctId));
        }
        for (AggregateResult aggr: [select AccountId Id, COUNT(Id) contactCount, SUM(Salary__c) salarySum, AVG(Salary__c) salaryAverage, MAX(Salary__c) salaryMax, MIN(Salary__c) salaryMin from Contact where AccountId =: conSetIds GROUP BY AccountId]) {
            conMapId.get((Id) aggr.get('Id')).Contact_Count__c      = (Decimal) aggr.get('contactCount') > 0  ? (Decimal) aggr.get('contactCount')   : 0;
            conMapId.get((Id) aggr.get('Id')).Contact_Sum_Salary__c = (Decimal) aggr.get('salarySum') > 0     ? (Decimal) aggr.get('salarySum')      : 0;
            conMapId.get((Id) aggr.get('Id')).Contact_Avg_Salary__c = (Decimal) aggr.get('salaryAverage') > 0 ? (Decimal) aggr.get('salaryAverage')  : 0;
            conMapId.get((Id) aggr.get('Id')).Contact_Max_Salary__c = (Decimal) aggr.get('salaryMax') > 0     ? (Decimal) aggr.get('salaryMax')      : 0;
            conMapId.get((Id) aggr.get('Id')).Contact_Salary_Min__c = (Decimal) aggr.get('salaryMin') > 0     ? (Decimal) aggr.get('salaryMin')      : 0;
        }
        update conMapId.values();
    }

}

jQuery with callouts and Lightning Process

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/multiple-select/1.2.0/multiple-select.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/multiple-select/1.2.0/multiple-select.js"></script>
<script>
$(document).ready(function() {
$.get("https://restcountries.eu/rest/v2/all", function(response) {
$.each(response, function(idx, obj) {
var select = $("#countValues");
$('<option>').val(obj.name).text(obj.name).appendTo(select);
});
});
var select1 = $("#myTable");
select1.empty();
var cstmTr1 = '<thead style="background: lightskyblue;"><tr>' +
'<th>Flag</th>' +
'<th>Name</th>' +
'<th>TopLevel Domain</th>' +
'<th>Alpha Code</th>' +
'<th>Alpha Code</th>' +
'<th>Calling Codes</th>' +
'<th>Capital</th>' +
'<th>Alt Spellings</th>' +
'<th>Region</th>' +
'<th>Subregion</th>' +
'<th>Population</th>' +
'<th>Latlng</th>' +
'<th>Demonym</th>' +
'<th>Area</th>' +
'<th>Gini</th>' +
'<th>Timezones</th>' +
'<th>Native Name</th>' +
'<th>Numeric Code</th>' +
'<th>Currencies</th>' +
'<th>Languages</th>' +
'</tr></thead>';
select1.attr('border', 2);
$(cstmTr1).appendTo(select1);
$('<tbody>').appendTo(select1);
var url = "https://restcountries.eu/rest/v2/all";
var select = $("#myTable tbody");
$.get(url, function(response) {
$.each(response, function(idx, obj) {
var cstmTr = '<tr>' +
'<td><img src="' + obj.flag + '" style="width:50px;height:50px;"/></td>' +
'<td>' + obj.name + '</td>' +
'<td>' + obj.topLevelDomain + '</td>' +
'<td>' + obj.alpha2Code + '</td>' +
'<td>' + obj.alpha3Code + '</td>' +
'<td>' + obj.callingCodes + '</td>' +
'<td>' + obj.capital + '</td>' +
'<td>' + obj.altSpellings + '</td>' +
'<td>' + obj.region + '</td>' +
'<td>' + obj.subregion + '</td>' +
'<td>' + obj.population + '</td>' +
'<td>' + obj.latlng + '</td>' +
'<td>' + obj.demonym + '</td>' +
'<td>' + obj.area + '</td>' +
'<td>' + obj.gini + '</td>' +
'<td>' + obj.timezones + '</td>' +
'<td>' + obj.nativeName + '</td>' +
'<td>' + obj.numericCode + '</td>' +
'<td>' + dynamicOption(obj.currencies) + '</td>' +
'<td>' + dynamicOption1(obj.languages) + '</td>' +
'</tr>';
$(cstmTr).appendTo(select);
});
});
});
$(document).on("change", "#countValues", function() {
var select1 = $("#myTable");
select1.empty();
var cstmTr1 = '<thead style="background: lightskyblue;"><tr>' +
'<th>Flag</th>' +
'<th>Name</th>' +
'<th>TopLevel Domain</th>' +
'<th>Alpha Code</th>' +
'<th>Alpha Code</th>' +
'<th>Calling Codes</th>' +
'<th>Capital</th>' +
'<th>Alt Spellings</th>' +
'<th>Region</th>' +
'<th>Subregion</th>' +
'<th>Population</th>' +
'<th>Latlng</th>' +
'<th>Demonym</th>' +
'<th>Area</th>' +
'<th>Gini</th>' +
'<th>Timezones</th>' +
'<th>Native Name</th>' +
'<th>Numeric Code</th>' +
'<th>Currencies</th>' +
'<th>Languages</th>' +
'</tr></thead>';
select1.attr('border', 2);
$(cstmTr1).appendTo(select1);
$('<tbody>').appendTo(select1);
var countryValue = this.value;
var url = "https://restcountries.eu/rest/v2/name/" + countryValue;
var select = $("#myTable tbody");
$.get(url, function(response) {
$.each(response, function(idx, obj) {
var cstmTr = '<tr>' +
'<td><img src="' + obj.flag + '" style="width:50px;height:50px;"/></td>' +
'<td>' + obj.name + '</td>' +
'<td>' + obj.topLevelDomain + '</td>' +
'<td>' + obj.alpha2Code + '</td>' +
'<td>' + obj.alpha3Code + '</td>' +
'<td>' + obj.callingCodes + '</td>' +
'<td>' + obj.capital + '</td>' +
'<td>' + obj.altSpellings + '</td>' +
'<td>' + obj.region + '</td>' +
'<td>' + obj.subregion + '</td>' +
'<td>' + obj.population + '</td>' +
'<td>' + obj.latlng + '</td>' +
'<td>' + obj.demonym + '</td>' +
'<td>' + obj.area + '</td>' +
'<td>' + obj.gini + '</td>' +
'<td>' + obj.timezones + '</td>' +
'<td>' + obj.nativeName + '</td>' +
'<td>' + obj.numericCode + '</td>' +
'<td>' + dynamicOption(obj.currencies) + '</td>' +
'<td>' + dynamicOption1(obj.languages) + '</td>' +
'</tr>';
$(cstmTr).appendTo(select);
});
});
});
function dynamicOption(parameter1) {
$select = $('<select></select>', {
"class": "fazu"
});
var tempString = '';
$.each(parameter1, function(index, value) {
tempString += value.code+",";
tempString += value.name+",";
tempString += value.symbol;
});
for(var temp in tempString.split(",")){
console.log("tempString value ::"+tempString.split(",")[temp]);
var $option = $("<option></option>", {
"text": tempString.split(",")[temp],
"value": tempString.split(",")[temp]
});
$select.append($option);
}
return $select.prop("outerHTML");
}
function dynamicOption1(parameter1) {
$select = $('<select></select>', {"class": "fazu"});
var tempString = '';
$.each(parameter1, function(index, value) {
console.log(JSON.stringify(value));
tempString += value.iso639_1+","+value.iso639_2+","+value.name+","+value.nativeName;
});
for(var temp in tempString.split(",")){
console.log("tempString value ::"+tempString.split(",")[temp]);
var $option = $("<option></option>", {
"text": tempString.split(",")[temp],
"value": tempString.split(",")[temp]
});
$select.append($option);
}
return $select.prop("outerHTML");
}
</script>
</head>
<body>
<select id="countValues"></select>
<br/>
<table id="myTable">
<tbody></tbody>
</table>
</body>
</html>


Integration between Spark to salesforce using Gupshup platform salesforce

Code Here :

/*
 * ******************************************************************************************************************
 * Author        : Fazurulla Ganganapalli
 * Controller    : MarketingBot.js
 * Marketing Bot : This controller is rsponsible for integration  between Spark to salesforce using Gupshup platform
 * Date          : 05/13/2017
 * History       :
 *******************************************************************************************************************
 */

//Variable declaration
var access_token = null;
var choiceString = '';
var moreChoiceString = '';
var userName ='';
var listLeadIds = '';
var choiceUniqueNumber;
var firstName ='';
var mainQuery = '';
var lastName='';
var userCECId='';
var contactCenter ='';
var profileName = '';
var tempAppString ='';
var tempSplitGreetString ='';
var permissionSet = '';
var userID_P = '';
var userPermission_P = '';

//Salesforce Oauth 2.0 settings and url's
var url_AccessToken = "https://login.salesforce.com/services/oauth2/token";
var url_getMethodAuth = "https://ap1.salesforce.com/services/data/v20.0/sobjects/Marketing_ChatBot__c/Application__c";
var authParams = "grant_type=password&client_id=3MVG9Y6d_Btp4xp5fHfBCvTWgHlfBKxrEf0lFIt9p71zfTmei0q9P8QxoaRowTIefchOoNdY8syyWOriUKYlV&client_secret=7975635620731036814&redirect_uri=https://localhost:8443/_callback&username=apex_integration@sfdc.com&password=Mardal786*k7Q58cu1ffXZEm0NOEgWi8vIv";
var authHeader = {"Content-Type":"application/x-www-form-urlencoded"};
var leadReopen_Url = "https://ap1.salesforce.com/services/apexrest/marketingActivities";
var url_CompleteApps = "https://ap1.salesforce.com/services/apexrest/marketingChatBotOprions";
var url_Application ="https://ap1.salesforce.com/services/apexrest/marketingChatBot";

//@Method : This method is responsible for handling choice based options
function MessageHandler(context, event) {
    var StrMain = event.message;
    var splitString = "ngcc,mods,jifflenow,grs,eloqua,cpc";
var splitGreetString ="Hi,hi,Hello,hello,Bot,bot,Chatbot,chatbot,Marketing,marketing,SFDC,Sfdc,sfdc";

    if(splitString != "" || splitString != NULL){
        var resString = splitString.split(",");
        for(var i in resString){
            if(resString[i] == StrMain){
                tempAppString = resString[i];
                context.console.log("tempAppString---->>>>"+tempAppString);
            }
        }
    }

if(splitGreetString != "" || splitGreetString != NULL){
        var resString = splitGreetString.split(",");
        for(var i in resString){
            if(resString[i] == StrMain){
                tempSplitGreetString = resString[i];
                context.console.log("tempSplitGreetString---->>>>"+tempSplitGreetString);
            }
        }
    }

    if(event.message.toLowerCase() == tempSplitGreetString){
        context.sendResponse("Hello There- \n"+
            "Welcome to Markting Bot- \n"+
            "I. Help (This will provide quick help  about the issues in an application which we  get on daily basis)\n "+
            "II. Lead (This would help to Re-Open closed leads) \n "+
            "II. Access (We will be able to  create new users in SFDC through Spark) \n "
        );
    }else if(event.message.toLowerCase() == "your from which location"){
        context.sendResponse("I am from Bengalore City");
    }else if(event.message.toLowerCase() == "fine thanks" || event.message.toLowerCase() == "fine"){
        context.sendResponse("Ok. How may i help you today !");
    }else if(event.message.toLowerCase() == "what is your name"){
        context.sendResponse("My name is Marketing Bot");
    }else if(event.message.toLowerCase() == "may i know you name"){
        context.sendResponse("My name is Marketing Bot");
    }else if(event.message.toLowerCase() == "how are you"){
        context.sendResponse("I am doing great thanks..How about you ?");
    }else if(event.message.toLowerCase() == "I need some help from you"){
        context.sendResponse("Sure. How can I help you today?");
    }else if(event.message.toLowerCase() == "how can i start"){
        context.sendResponse("Search with any keyword like : help, lead, access");
    }else if(event.message.toLowerCase() == "bye"){
        context.sendResponse("Bye have a good day !");
    }else if(event.message.toLowerCase() == "help"){
        context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setApplication);
       
    //*******************************************Applciation Search Start here********************************************************
    }else if(event.message.toLowerCase() == "ngcc"){
        moreChoiceString = event.message;
        context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setHelp);
    }else if(event.message.toLowerCase() == "mods"){
        moreChoiceString = event.message;
        context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setHelp);
    }else if(event.message.toLowerCase() == "jifflenow"){
        moreChoiceString = event.message;
        context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setHelp);
    }else if(event.message.toLowerCase() == "grs"){
        moreChoiceString = event.message;
        context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setHelp);
    }else if(event.message.toLowerCase() == "eloqua"){
        moreChoiceString = event.message;
        context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setHelp);
    }else if(event.message.toLowerCase() == "cpc"){
        moreChoiceString = event.message;
        context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setHelp);
       
    //*****************************************Application Search end here**********************************************************
    }else if(event.message.toLowerCase() == "lead"){
        context.sendResponse(
            "Please make a selection - \n"+
            "A). Lead Re-Open \n "+
            "B). Access Help\n "+
            "C). Create New User/Access Provide\n "+
            "D). Assign Permission Sets\n "+
"E). SOQL Records\n "
        );
    }else if(event.message.toLowerCase() == "access"){
        context.sendResponse(
            "Please make a selection - \n"+
            "A). Lead Re-Open \n "+
            "B). Access Help\n "+
            "C). Create New User\n "+
            "D). Assign Permission Sets\n "+
"E). SOQL Records\n "
        );
    }else{
        var StrMain = event.message;
        var res = StrMain.split(/,|:|-| /);
        for(var i in res){
            if(i==0){
                choiceString = res[i];
            }else if(i==1){
                userName = res[i];
            }else{
                listLeadIds += res[i]+",";
            }
        }
       
        for(var i in res){
            if(i==0){
                choiceString = res[i];
            }else if(i==1){
                firstName = res[i];
            }else if(i==2){
                lastName = res[i];
            }else if(i==3){
                userCECId = res[i];
            }else if(i==4){
                contactCenter = res[i];
            }else if(i==5){
                profileName = res[i];
            }else if(i==6){
                permissionSet = res[i];
            }
        }
        var permissionString = event.message;
        var permission = permissionString.split(' ');
        for(var i in permission){
            if(i==0){
                choiceString = permission[i];
            }else if(i==1){
                userID_P = permission[i];
            }else{
                userPermission_P += permission[i]+",";
            }
        }

var soqlQuery = event.message;
        var soql = soqlQuery.split(' ');
        for(var i in soql){
            if(i==0){
                choiceString = soql[i];
            }else{
                mainQuery += soql[i]+" ";
            }
        }
       
        if(choiceString.toLowerCase() == "a"){
            context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setNGCC);
        }else if(choiceString.toLowerCase() == "b"){
            context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setAccessProfile);
        }else if(choiceString.toLowerCase() == "c"){
            context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setUserCreation);
        }else if(choiceString.toLowerCase() == "d"){
            context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setUserPermission);
        }else if(choiceString.toLowerCase() == "e"){
            context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setSOQL);
        }else if(event.message.toLowerCase() == StrMain){
            choiceUniqueNumber = event.message;
            context.simplehttp.makePost(url_AccessToken,authParams,authHeader,setNumbers);
        }else{
            context.sendResponse("Sorry you have entered an invalid keyword");
        }
    }
}

//***************************************************************************************************
//@Method : Responsible for iterate response and get values from salesforce.com database
function setNGCC(context,event){
    if(userName ==''&& listLeadIds ==''){
        context.sendResponse(
            "Please enter User CECID and list of Lead IDs.Below are the possible ways to follow- \n"+
            "I. A,UserID,Single LeadID or List of LeadIDs(Separated with comma) \n"+
            "II. A UserID Single LeadID or List of LeadIDs(separated with space)\n"             
        );
    }else{
    var result= JSON.parse(event.getresp);
    access_token = result.access_token;
    context.simplehttp.makeGet(leadReopen_Url+"?username="+userName+"&LeadId="+listLeadIds,{"Content-Type":"application/json","Authorization":"OAuth "+access_token},getNGCC);
    }
}

//@Method: Responsible for iterating and parsing JSON response into user understandable language
function getNGCC(context,event){
   context.sendResponse(event.getresp);
}
//@Method : Responsible for iterate response and get values from salesforce.com database
function setNumbers(context,event){
     var result= JSON.parse(event.getresp);
    access_token = result.access_token;
    context.simplehttp.makeGet("https://ap1.salesforce.com/services/data/v20.0/sobjects/Marketing_ChatBot__c/Choice_Unique_Number__c/"+choiceUniqueNumber,{"Content-Type":"application/json","Authorization":"OAuth "+access_token},getNumbers);
}

//@Method: Responsible for iterating and parsing JSON response into user understandable language
function getNumbers(context,event){
    //context.sendResponse(event.getresp);
    var contacts  = JSON.parse(event.getresp);
    var tempStr = '';
       var Application__c = contacts.Application__c;
       var Entity__c = contacts.Entity__c;
       var Issue__c = contacts.Issue__c;
       var Solution__c = contacts.Solution__c;
       var Description__c = contacts.Description__c;
       tempStr += "Application Name :"+Application__c+"\n Entity Name : "+Entity__c+"\n Issue : "+Issue__c+"\n Issue Description :"+Solution__c+"\n Answer Steps : \n"+Description__c+"\n";
   context.sendResponse(tempStr);
 
}
//***************************************************************************************************

//***************************************************************************************************
//@Method : Responsible for iterate response and get values from salesforce.com database
function setApplication(context,event){
     var result= JSON.parse(event.getresp);
    access_token = result.access_token;
    context.simplehttp.makeGet(url_Application,{"Content-Type":"application/json","Authorization":"OAuth "+access_token},getApplication);
}

//@Method: Responsible for iterating and parsing JSON response into user understandable language
function getApplication(context,event){
    //context.sendResponse(event.getresp);
   var contacts  = JSON.parse(event.getresp);
   var tempStr = '';
   for(var i in contacts){
       tempStr +="*. "+i+"\n";
   }
   context.sendResponse("Please make a selection - \n"+tempStr);
}
//***************************************************************************************************

//***************************************************************************************************
//@Method : Responsible for iterate response and get values from salesforce.com database
function setHelp(context,event){
     var result= JSON.parse(event.getresp);
    access_token = result.access_token;
    context.simplehttp.makeGet(url_CompleteApps+'/'+moreChoiceString,{"Content-Type":"application/json","Authorization":"OAuth "+access_token},getHelp);
}

//@Method: Responsible for iterating and parsing JSON response into user understandable language
function getHelp(context,event){
    var contacts  = JSON.parse(event.getresp);
    var tempStr = '';
    for(var i in contacts){
       tempStr +=i+". "+contacts[i]+"\n";
   }
   context.sendResponse("Please Search with numbers only-\n\n"+tempStr);
}
//***************************************************************************************************
function EventHandler(context, event) {
    if(! context.simpledb.botleveldata.numinstance)
        context.simpledb.botleveldata.numinstance = 0;
        numinstances = parseInt(context.simpledb.botleveldata.numinstance) + 1;
        context.simpledb.botleveldata.numinstance = numinstances;
        context.sendResponse("Thanks for adding me. You are:" + numinstances);
}

function setAccessProfile(context,event){
     var result= JSON.parse(event.getresp);
    access_token = result.access_token;
    context.simplehttp.makeGet("https://ap1.salesforce.com/services/apexrest/marketingActivitiesUser",{"Content-Type":"application/json","Authorization":"OAuth "+access_token},getAccessProfile);
}

//@Method: Responsible for iterating and parsing JSON response into user understandable language
function getAccessProfile(context,event){
   var contacts  = JSON.parse(event.getresp);
    var tempStr = '';
    for(var i in contacts){
       tempStr +=i+" - "+contacts[i]+"\n";
   }
   context.sendResponse("\n"+tempStr);
}
//***************************************************************************************************
//@Method : Responsible for iterate response and get values from salesforce.com database
function setUserCreation(context,event){
    if(firstName =='' && lastName =='' && userCECId =='' && contactCenter =='' && profileName==''&& permissionSet==''){
        context.sendResponse(
            "Please provide the below details- \n"+
            "I. Option you need to select - C \n"+
            "II. First Name\n" +
            "III. Last Name\n"+
            "IV. User CEC ID\n"+
            "V. Marketing Contact Center(Press *B* and copy paste your Contact Center)\n"+
            "V. User Profile Name(Press *B* you will get help from SFDC)\n"+
            "VI. Permission Set (Press *B* you will get help from SFDC)\n"
        );
    }else{
        var result= JSON.parse(event.getresp);
        access_token = result.access_token;
        context.simplehttp.makeGet("https://ap1.salesforce.com/services/apexrest/marktingUserCreating?firstName="+firstName+"&lastName="+lastName+"&userId="+userCECId+"&contactCenter="+contactCenter+"&profileName="+profileName+"&permissionSet="+permissionSet,{"Content-Type":"application/json","Authorization":"OAuth "+access_token},getUserCreation);
    }
}

//@Method: Responsible for iterating and parsing JSON response into user understandable language
function getUserCreation(context,event){
   context.sendResponse(event.getresp);
}

function setUserPermission(context,event){
if(userID_P =='' && userPermission_P ==''){
        context.sendResponse(
            "Please provide the below details- \n"+
            "I. Option you need to select as - D \n"+
            "II. Provide User CEC ID\n" +
            "III. List of Permission Sets\n"
        );
    }else{
     var result= JSON.parse(event.getresp);//setSOQL
    access_token = result.access_token;
    context.simplehttp.makeGet("https://ap1.salesforce.com/services/apexrest/marktingUserCreatingPermissions?userId="+userID_P+"&permissions="+userPermission_P,{"Content-Type":"application/json","Authorization":"OAuth "+access_token},getUserPermission);
}
}

//@Method: Responsible for iterating and parsing JSON response into user understandable language
function getUserPermission(context,event){
    context.sendResponse(event.getresp);
}
function setSOQL(context,event){
    if(userID_P =='' && userPermission_P ==''){
        context.sendResponse(
            "Please provide the below details- \n"+
            "I. Option you need to select as - E \n"+
            "II. Write SOQL query "
        );
    }else{
var result= JSON.parse(event.getresp);//setSOQL
access_token = result.access_token;
context.simplehttp.makeGet("https://ap1.salesforce.com/services/data/v20.0/query/?q="+mainQuery,{"Content-Type":"application/json","Authorization":"OAuth "+access_token},getSOQL);
}
}

//@Method: Responsible for iterating and parsing JSON response into user understandable language
function getSOQL(context,event){
    var contacts  = JSON.parse(event.getresp);
    context.sendResponse("\n"+event.getresp);
    var tempStr = '';
var TotalSize = contacts.totalSize;
    var Status = contacts.done;
    tempStr +="TotalSize : "+TotalSize+"\n Status : "+Status+"\n";
    var recordsList = contacts.records;
    //context.sendResponse("\n"+recordsList);
    for(var i in recordsList){
       
        if(recordsList[i].Id == ''){}
        else
        tempStr += "Id :"+recordsList[i].Id+"\n";
       
        if(recordsList[i].Username == ''){}
        else
        tempStr += "Username :"+recordsList[i].Username+"\n";
       
        if(recordsList[i].FirstName == ''){}
        else
        tempStr += "FirstName :"+recordsList[i].FirstName+"\n";
       
        tempStr += "LastName :"+recordsList[i].LastName+"\n";
        tempStr += "Name :"+recordsList[i].Name+"\n";
        tempStr += "Title :"+recordsList[i].Title+"\n";
        tempStr += "CompanyName "+recordsList[i].CompanyName+"\n";
        tempStr += "Address :"+recordsList[i].Address+"\n";
        tempStr += "Email "+recordsList[i].Email+"\n";
        tempStr += "Phone :"+recordsList[i].Phone+"\n";
        tempStr += "CommunityNickname :"+recordsList[i].CommunityNickname+"\n";
        tempStr += "UserRoleId :"+recordsList[i].UserRoleId+"\n";
        tempStr += "ProfileId :"+recordsList[i].ProfileId+"\n";
        tempStr += "UserPermissionsMarketingUser :"+recordsList[i].UserPermissionsMarketingUser+"\n";
        tempStr += "UserPermissionsSupportUser :"+recordsList[i].UserPermissionsSupportUser+"\n";
        tempStr += "Marketing_Call_Center__c : "+recordsList[i].Marketing_Call_Center__c+"\n";
    }
   //context.sendResponse("\n"+tempStr);
}


//######
//Auto generated code from devbox
//######

exports.onMessage = MessageHandler;
exports.onEvent = EventHandler;
exports.onHttpResponse = HttpResponseHandler;
exports.onDbGet = DbGetHandler;
exports.onDbPut = DbPutHandler;
if(typeof LocationHandler == 'function'){exports.onLocation = LocationHandler;}

if(typeof  HttpEndpointHandler == 'function'){exports.onHttpEndpoint = HttpEndpointHandler;}

Parent field update with all related childs in salesforce

Trigger :

trigger answerOptionManagement on Employees__c (before update) {
    Set<Id> setIDS = new Set<Id>();
    List<Employees__c> listIDS = new List<Employees__c>();
    for(Employees__c  emp : trigger.new){
        setIDS.add(emp.Id);
        listIDS.add(emp);
    }
    if(!listIDS.isEmpty() && listIDS.size()>0){
        cmdMainOperation(listIDS,setIDS);
    }
    public static void cmdMainOperation(List<Employees__c> listIDS,Set<Id> setIDS){
        AggregateResult [] aggr = [select count(id),First_Name__c fristName,Employees__c employeeId from Contact_Us__c where Employees__c IN :setIDS and First_Name__c != null group by First_Name__c,Employees__c  order by First_Name__c desc];
        system.debug(aggr);
        Map<Id,String> mapAggr = new Map<Id,String>();
        for(AggregateResult agr : aggr){           
            system.debug(mapAggr);
            string category=String.valueOf(agr.get('fristName'));
            category = category.subString(category.indexOf(':')+1,category.length());
            if(mapAggr.containsKey(String.valueOf(agr.get('employeeId')))){
                String strCategory = mapAggr.get(String.valueOf(agr.get('employeeId')))+ ','+category;
                mapAggr.put(String.valueOf(agr.get('employeeId')),strCategory );
                system.debug('mapAggr in if 21 line--->>'+mapAggr);
            }else{
                mapAggr.put(String.valueOf(agr.get('employeeId')),category);
                system.debug('mapAggr in if 24 line--->>'+mapAggr);
            }
        }
        for(Employees__c emp : listIDS){
            if(mapAggr.containsKey(emp.id)){
                emp.Answer_Options__c = mapAggr.get(emp.id);
                system.debug('emp.Answer_Options__c in if 30 line--->>'+emp.Answer_Options__c);
            }
           
        }
       
    }

}

Standard Report charts in Lightning component Salesforce

Create summary report using standard Report tab. For this example, I have created a simple report which groups ContactUS__c by City__c.

Apex code snippet :

public class ChartOnContactUS {
    @AuraEnabled
    public static List<Report> getDynamicReport(){
        return [SELECT Id,Name FROM Report];
    }
    @AuraEnabled
    public static String getreport(String reportId){
        Report reportRec = [SELECT Id FROM Report WHERE Id =:reportId];
        Reports.ReportResults reportResult = Reports.ReportManager.runReport(reportRec.Id, true);
        system.debug(JSON.serialize(reportResult));
        return JSON.serialize(reportResult);
    }
}

ChartComponent.cmp

<aura:component controller="ChartOnContactUS" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <ltng:require scripts="{!$Resource.ChartJs}"  afterScriptsLoaded="{!c.afterScriptsLoaded}"/>
    <aura:attribute name="ready" type="Boolean" default="false"/>
    <aura:attribute name="countryName" type="String" default="00O0Y000007eZRnUAM"/>
    <aura:attribute name="report" type="sobject"/>
    <div class="slds-grid slds-p-top_small">
                <div class="slds-size_4-of-12 slds-p-left_xx-small slds-p-horizontal_x-large ">
                    <lightning:select label="Report Name" value="{!v.countryName}"  onchange="{!c.cmdCountryEvt}">>
                        <aura:iteration items="{!v.report}" var="reportValue">
                            <option value="{!reportValue.Id}">{!reportValue.Name}</option>
                        </aura:iteration>
                    </lightning:select>
                </div>
            </div>
    <div class="slds-grid slds-wrap slds-grid--pull-padded ">
        <div class="slds-p-horizontal--small slds-size--1-of-3 slds-m-top--medium">
            <canvas aura:id="chart" height="200" width="200"></canvas>
        </div>
    </div>
</aura:component>

ChartComponentController.js

({
    afterScriptsLoaded : function(component, event, helper) {
        component.set("v.ready", true);
        helper.createChart(component);
        helper.cmdDynamicRepor(component);
    },
    cmdCountryEvt : function(component,event,helper){
        console.log(component.get("v.countryName"));
helper.createChart(component);     
    }
 
})

ChartComponentHelper.js

({
    createChart : function (component) {
        var chartCanvas = component.find("chart").getElement();
        var action = component.get("c.getreport");
        action.setParams({reportId : component.get("v.countryName")});
        action.setCallback(this, function(response) {
            console.log("faz response"+JSON.stringify(response.getReturnValue()));
            var state = response.getState();
            if (state === "SUCCESS") {
                var reportResultData = JSON.parse(response.getReturnValue());
                var chartData = [];
                var chartLabels = [];
                if( reportResultData.groupingsDown.groupings.length > 0  ) {
                    for(var i=0; i < (reportResultData.groupingsDown.groupings.length); i++){
                        chartLabels.push(reportResultData.groupingsDown.groupings[i].label);
                        var keyTemp = reportResultData.groupingsDown.groupings[i].key;
                        var valueTemp = reportResultData.factMap[keyTemp + '!T'].aggregates[0].value ;
                        chartData.push(valueTemp);
                    }
                    console.log(" chartLabels ::  " + JSON.stringify(chartLabels));
                    console.log( " chartData :: " + JSON.stringify(chartData));                 
                    var chartdata = {
                        labels: chartLabels,
                        datasets: [
                            {
                                label:'Country',
                                data: chartData,
                                borderColor:'rgba(62, 159, 222, 1)',
                                fill: false,
                                pointBackgroundColor: "#FFFFFF",
                                pointBorderWidth: 4,
                                pointHoverRadius: 5,
                                pointRadius: 3,
                                bezierCurve: true,
                                pointHitRadius: 10
                            }
                        ]
                    }
                    var ctx = component.find("chart").getElement();
                    var chart = new Chart(ctx ,{
                        type: 'line',
                        data: chartdata,
                        options: {
                            legend: {
                                position: 'bottom',
                                padding: 10,
                            },
                            responsive: true
                        }
                    });                 
                }
            } else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message on createReport: " +errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    cmdDynamicRepor : function(component,event,helper){
        var dynamicPicklist = component.get("c.getDynamicReport");
        dynamicPicklist.setCallback(this,function(response){
            console.log("getDynamicReport====>>"+JSON.stringify(response.getReturnValue()));
            if(response.getState() === "SUCCESS"){
                component.set("v.report",response.getReturnValue());
            }
        });
        $A.enqueueAction(dynamicPicklist);
    }
})

D3ComponentApp 

<aura:application extends="force:slds">
<c:ChartComponent ></c:ChartComponent>
</aura:application>

Screenshot



Featured

What is Cryptography in salesforce and what are all the algorithms provided by them ?

A). It is a security protocal between two systems. Lets say we are integration two systems without any encrytion mechanism then hackers wil...

Popular