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



Salesforce Lightning Events with example

Passing values from child component to parent component using Lightning Events.

CeeeEvent:

<aura:event type="COMPONENT">
    <aura:attribute name="firstName" type="String"/>
    <aura:attribute name="lastName" type="String"/>
    <aura:attribute name="emailId" type="String"/>
    <aura:attribute name="mobileNumber" type="String"/>
    <aura:attribute name="contactDetails" type="Contact[]"/>

</aura:event>

Child component : CeeeCmponent1

<aura:component controller="contactHanler">
    <aura:attribute name="firstName" type="String"/>
    <aura:attribute name="lastName" type="String"/>
    <aura:attribute name="emailId" type="String"/>
    <aura:attribute name="mobileNumber" type="String"/>
    <aura:attribute name="contactDetails" type="Contact[]"/>
    <aura:registerEvent name="cmpEvent" type="c:CeeeEvent"/>
    <lightning:input type="text" label="First Name" value="{!v.firstName}"/>
    <lightning:input type="text" label="Last Name" value="{!v.lastName}"/>
    <lightning:input type="text" label="Email ID" value="{!v.emailId}"/>
    <lightning:input type="text" label="Phone" value="{!v.mobileNumber}"/>
    <lightning:button  label="Search" onclick="{!c.fireComponentEvent}" />

</aura:component>


ControllerJS :

({
    fireComponentEvent : function(cmp, event) {
        var cmpEvent = cmp.getEvent("cmpEvent");
        var action = cmp.get("c.getAFewContacts");
        action.setCallback(this,function(response){
            console.log("response.getState---"+response.getState());
            console.log("response.code---"+response.getReturnValue());
            cmp.set("v.contactDetails",response.getReturnValue());
            if(response.getState() === "SUCCESS"){
                cmpEvent.setParams({
                    "firstName"       :  cmp.get("v.firstName"),
                    "lastName"        :  cmp.get("v.lastName"),
                    "emailId"         :  cmp.get("v.emailId"),
                    "mobileNumber"    :  cmp.get("v.mobileNumber"),
                    "contactDetails"  :  cmp.get("v.contactDetails")
                });
                cmpEvent.fire();
                console.log("contact list---"+JSON.stringify(cmp.get("v.contactDetails")));
            }
        });
        $A.enqueueAction(action);
    }

})

Parent Handler : CeeeParentHandler

<aura:component>
    <aura:attribute name="firstName"     type="String"/>
    <aura:attribute name="lastName"      type="String"/>
    <aura:attribute name="emailId"       type="String"/>
    <aura:attribute name="mobileNumber"  type="String"/>
    <aura:attribute name="contactDetails" type="Contact[]"/>
    <aura:attribute name="numEvents"     type="Integer"       default="0"/>
    <aura:handler   name="cmpEvent"      event="c:CeeeEvent"  action="{!c.handleComponentEvent}"/>
    <c:CeeeCmponent1/>
    <p>{!v.firstName}</p>
    <p>{!v.lastName}</p>
    <p>{!v.emailId}</p>
    <p>{!v.mobileNumber}</p>
    <p>Number of events: {!v.numEvents}</p>
    <aura:iteration items="{!v.contactDetails}" var="item">
        {!item.Id}{!item.Email}<br/>
    </aura:iteration>
</aura:component>

ControllerJS:

({
    handleComponentEvent : function(cmp, event) {
        console.log(event.getParams().firstName);
        console.log(event.getParams().lastName);
        console.log(event.getParams().emailId);
        console.log(event.getParams().mobileNumber);
        cmp.set("v.firstName",        event.getParams().firstName);
        cmp.set("v.lastName",         event.getParams().lastName);
        cmp.set("v.emailId",          event.getParams().emailId);
        cmp.set("v.mobileNumber",     event.getParams().mobileNumber);
        cmp.set("v.contactDetails",   event.getParams().contactDetails);
        var numEventsHandled = parseInt(cmp.get("v.numEvents")) + 1;
        cmp.set("v.numEvents",      numEventsHandled);
    }
})

Apex Controller : contactHanler

public class contactHanler {
    @AuraEnabled public static List<Contact> getAFewContacts(){
        return [select Id,Name,Email from contact];
    }
}

CeeeHandlerApp :


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









Salesforce Database.saveResult and Database.Error example

Code snippet :

List<Contact> con = [select id,lastname,AccountId from contact order by createddate desc Limit 20];
//Map<Id,Contact> conAcc = new Map<Id,Contact>();
Set<Id> conSet = new Set<Id>();
for(contact conn : con){
    if(String.isNotBlank(conn.AccountId)){
        conSet.add(conn.AccountId);
    }
}
Map<Id,Account> conAcc = new Map<Id,Account>([select Id,name from account where Id IN : conSet]);
for(contact connn :con){
    if(conAcc.containsKey(connn.AccountId)){
        connn.lastname = connn.lastname +'--'+ conAcc.get(connn.AccountId).name;
    }
}
Database.SaveResult[] res = database.update(con,false);
List<Database.Error> dError = new List<Database.Error>();
system.debug(res);
for(Database.SaveResult result :res){
    if(result.isSuccess()){
        system.debug('Pass--->>'+result.getId());
    }else{
        system.debug('faled--->>'+result.getErrors());
        dError.addAll(result.getErrors());       
    }
}
for(Database.Error r : dError){
    system.debug('Fields ---->>>'+r.getFields());
    system.debug('Messages ---->>>'+r.getMessage());
    system.debug('Status Code ---->>>'+r.getStatusCode());

}



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