Salesforce Interview Preparation:
1. Batch Apex: is asynchronous apex used to process the records in the background without user having to wait to complete the task.
global class sampleBatchClass implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext bc){
return Database.getQueryLocator('SELECT Id FROM Account WHERE CreateDate < LAST_N_DAYS:7');
}
global void execute(Database.BatchableContext bc, List<Account> accts){
if(!accts.isEmpty){
try {
Database.Delete(accts, false);
}
catch(Exception ex){
System.debug('Exception occurred '+ex);
}
}
}
global void finish(Database.BatchableContext bc){
}
}
2. Schedulable Apex: is asynchronous process used to schedule the batch apex from Salesforce UI.
To schedule apex class ==> go to Apex Classes ==> Click on "Schedule Apex" button ==> Select class and time.
global class sampleSchedulableClass implements Schedulable {
global void execute(SchedulableContext sc){
sampleBatchClass s = new sampleBatchClass();
Database.executeBatch(s, 200);
}
}
Scheduled Apex Class Using Cron Expression:
AccountBatchScheduled apexSch = new AccountBatchScheduled();
//Seconds, Minutes, Hours, Day of month, Month, Day of week, Optional year
String CRON_EXP = '0 0 0 3 9 2 ?';
String jobID = System.schedule('AccountBatchScheduled Job', CRON_EXP, apexSch);
0 0 13 * * ? ==> Class runs every day at 1 PM.
public class sampleFutureClass {
@future
public static void methodName(List<Id> accountIds){
// logic
}
}
4. Queueable Apex: You can chain one job to another job by starting a second job from a running job. Chaining jobs are useful when we need to do some sequential processing.
public class sampleQueueableClass implements Queueable {
public void execute(QueueableContext qc){
// logic
}
}
5. Apex Trigger: is apex code which will execute before/after DML operation is performed on the database.
Apex Trigger events: BEFORE INSERT, BEFORE UPDATE, BEFORE DELETE, AFTER INSERT, AFTER UPDATE, AFTER DELETE, AFTER UNDELETE.
Context variables: IsBefore, IsAfter, IsInsert, IsUpdate, IsDelete, IsUndelete.
Trigger:
Trigger AccountTrigger on Account(Before Insert, Before Update, Before Delete,
After Insert, After Update, After Delete, After Undelete){
if(Trigger.IsAfter){
if(Trigger.isInsert){
AccountTriggerHelper.createContact(Trigger.new);
}
}
}
After Insert, After Update, After Delete, After Undelete){
if(Trigger.IsAfter){
if(Trigger.isInsert){
AccountTriggerHelper.createContact(Trigger.new);
}
}
}
Trigger Helper Class:
public class AccountTriggerHelper {
public static void createContact(List<Account> listAcc){
List<Contact> listCon = new List<Contact>();
for(Account acc: listAcc){
Contact con = new Contact();
con.LastName = acc.Name;
con.AccountId = acc.Id;
listCon.add(con);
}
if(!listCon.isEmpty){
try {
Database.insert(listCon, false);
}
catch(Exception ex){
System.debug('Exception 'ex);
}
}
}
}
6. Apex Test Class: is used to test the apex code.
Test Class:
@isTest
public class sampleTestClass {
static testMethod void sampleMethod(){
LisT<Account> listAcc = TestDataUtility.createAccounts();
insert listAcc;
}
}
( or )
@isTest
public class sampleTestClass {
static testMethod void sampleMethod(){
Account acc = new Acount(Name = 'Test');
insert listAcc;
}
}
TestDataUtility class: is used to store bulk records in a separate class so that it can utilized whenever data is required in any test class.
public class sampleTestClass {
static testMethod void sampleMethod(){
Account acc = new Acount(Name = 'Test');
insert listAcc;
}
}
TestDataUtility class: is used to store bulk records in a separate class so that it can utilized whenever data is required in any test class.
public class TestDataUtility {
public static List<Account> createAccounts(){
List<Account> accts = new List<Account>();
for(Integer i=1; i<=20; i++){
Account acc = new Account();
acc.Name = ConstantUtility.accName + i;
acc.Description = ConstantUtility.stringDescription;
accts.add(acc);
}
return accts;
}
}
Constant Utility Class: is used to store constant values in a separate class so that it can be utlized wherever is required.
public class ConstantUtility {
public static String accName = 'Test Account';
public static String stringDescription = 'Sample Description';
}
7. SOAP Inbound Web Service: is used to capture the data from external system and store in Salesforce.
global class sampleClass {
webservice Static String createAccount(String accName){
Account acc = new Account();
acc.Name = accname;
if(acc != null){
try {
insert acc;
}
catch(Exception ex){
System.debug('Exception '+ex);
}
}
}
}
8. Rest Inbound Web Service: is used to capture the data from external system and store it in Salesforce org.
@RestResource(urlMapping = '/accounts/*')
global class sampleRestClass {
@HttpPost
global static Account createAccount(String accName){
Account acc = new Account(Name = accName);
insert acc;
return acc;
}
}
global class sampleRestClass {
@HttpPost
global static Account createAccount(String accName){
Account acc = new Account(Name = accName);
insert acc;
return acc;
}
}
9. Lightning AURA Component: is used to develop UI for salesforce applications.
AURA component to display records.
Server Side Controller:
public with sharing class sampleClass {
@AuraEnabled
public static List<Account> getAccountData(){
return [SELECT Id, Name FROM Account LIMIT 10];
}
}
Client Side Controller:
({
doInit: function(component){
var action = component.get('c.getAccountData');
var self = this;
action.setCallback(this, function(actionResult){
component.set('v.accList', actionResult.getReturnValue());
});
$A.enqueueAction(action);
}
})
Aura Component:
<aura:component implements="force:appHostable, flexipage:availableForAllPageTypes" controller="sampleClass">
<aura:handler name="init" value="{!this}" action="{!c.doinit}">
<aura:attribute name = "accList" type="list"/>
<aura:iteration items="{!v.accList}" var="item">
{!item.Name}
</aura:iteration>
</aura:component>
Aura App:
<aura:application extends="force:slds">
<c:DisplayAccounts>
</aura:application>
10. Lightning Web Component: is used to create UI for Salesforce applications.
LWC to display records:
Server Side Controller:
public class AccountController
{
@AuraEnabled(cacheable=true)
public static List<Account> displayAccounts(){
return [select Id, Name, Site from Account];
}
}
DisplayAccounts.html
<template>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td><b>Name</b></td>
</tr>
<template for:each={accounts.data} for:item="acc">
<tr key={acc.Id}>
<td>
{acc.Name}
</td>
</tr>
</template>
</table>
</template>
</template>
DisplayAccounts.js
import { LightningElement,api,wire } from 'lwc';
import displayAccounts from '@salesforce/apex/AccountController.displayAccounts';
export default class UpdateAccount extends LightningElement {
@wire(displayAccounts) accounts;
}
LightningApplication
<aura:application extends="force:slds">
<c:DisplayAccounts/>
</aura:application>
11. Trigger to fetch values from Custom Metadata type and update in ISO__c field of Account:
Trigger updateIsoCode on Contact(before insert) {
List < Country_ISO_Code__mdt > countryIsoCodeMetadata = [SELECT Id,
Country__c, ISO_Code__c FROM Country_ISO_Code__mdt
];
Map < String, String > countryIsoCodeMap = new Map < String, String > ();
if (countryIsoCodeMetadata != null && countryIsoCodeMetadata.size() > 0) {
for (Country_ISO_Code__mdt cmd: countryIsoCodeMetadata) {
countryIsoCodeMap.put(cmd.Country__c, cmd.ISO_Code__c);
}
}
for (Contact con: Trigger.new) {
if (countryIsoCodeMap.containsKey(con.Country__c)) {
System.debug('inside Contact loop @@@ ' + countryIsoCodeMap);
con.ISO_Code__c = countryIsoCodeMap.get(con.Country__c);
}
}
}
12. Trigger to prevent duplicate primary contacts:
Trigger PrimaryContactChecking on Contact(after insert, after update) {
Set < Id > accountIdSet = new Set < id > ();
Map < Id, List < Contact >> accountIdContactMap = new Map < Id, List < Contact >> ();
Account acc = new Account();
for (Contact con: Trigger.New) {
accountIdSet.add(con.AccountId);
}
for (Contact con: [SELECT Id, IsPrimaryContact__c, AccountId FROM Contact
WHERE AccountId =: accountIdSet AND IsPrimaryContact__c = TRUE
]) {
if (accountIdContactMap.containsKey(con.AccountId)) {
accountIdContactMap.get(con.AccountId).add(con);
} else {
accountIdContactMap.put(con.AccountId, new List < Contact > ());
accountIdContactMap.get(con.AccountId).add(con);
}
}
for (Contact con: Trigger.New) {
if ((accountIdContactMap.containsKey(con.AccountId)) &&
(con.AccountId != NULL) && (con.IsPrimaryContact__c == TRUE)) {
{
con.IsPrimaryContact__c.addError('Primary Contact already exists');
con.addError('Primary Contact already exists');
}
}
}
}
13. Rest callouts to send data to external syntax.
Apex Rest callout - POST:
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
request.setBody('{"name":"mighty moose"}');
HttpResponse response = http.send(request);
if (response.getStatusCode() != 201) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
}
14. Display and Update records using button in LWC:
Apex Class:
public class AccountController
{
@AuraEnabled(cacheable=true)
public static List<Account> displayAccounts(){
return [select Id,Name,Site from Account];
}
@AuraEnabled
public static List<Account> updateRecord(String accId){
Account acc=[select Id,Name,Site from Account where Id=:accId];
acc.site='Approved';
try{
update acc;
}
catch (Exception e) {
System.debug('unable to update the record due to'+e.getMessage());
}
return displayAccounts();
}
}
updateAccount.html
<template>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td><b>Name</b></td>
<td><b>Site</b></td>
<td><b>Action</b></td>
</tr>
<template for:each={accounts.data} for:item="acc">
<tr key={acc.Id}>
<td>
{acc.Name}
</td>
<td>
<lightning-button label="update" variant="brand" value={acc.Id} onclick={handleUpdate}>
</lightning-button>
</td>
</tr>
</template>
</table>
</template>
</template>
public class AccountController
{
@AuraEnabled(cacheable=true)
public static List<Account> displayAccounts(){
return [select Id,Name,Site from Account];
}
@AuraEnabled
public static List<Account> updateRecord(String accId){
Account acc=[select Id,Name,Site from Account where Id=:accId];
acc.site='Approved';
try{
update acc;
}
catch (Exception e) {
System.debug('unable to update the record due to'+e.getMessage());
}
return displayAccounts();
}
}
updateAccount.html
<template>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td><b>Name</b></td>
<td><b>Site</b></td>
<td><b>Action</b></td>
</tr>
<template for:each={accounts.data} for:item="acc">
<tr key={acc.Id}>
<td>
{acc.Name}
</td>
<td>
<lightning-button label="update" variant="brand" value={acc.Id} onclick={handleUpdate}>
</lightning-button>
</td>
</tr>
</template>
</table>
</template>
</template>
updateAccount.js
import { LightningElement,api,wire } from 'lwc';
import displayAccounts from '@salesforce/apex/AccountController.displayAccounts';
import updateRecord from '@salesforce/apex/AccountController.updateRecord';
import { refreshApex } from '@salesforce/apex';
export default class UpdateAccount extends LightningElement {
@api currentRecordId;
@api errorMessage;
@wire(displayAccounts) accounts;
handleUpdate(event){
this.currentRecordId=event.target.value;
console.log('@@currentRecordId@@@'+this.currentRecordId);
updateRecord({
accId:this.currentRecordId
})
.then(() => {
console.log('SUCCESS');
return refreshApex(this.accounts);
})
.catch((error) => {
this.errorMessage=error;
console.log('unable to update the record due to'+JSON.stringify(this.errorMessage));
});
}
}
15. AURA component to display and delete records:
public with sharing class AccountCtrl {
@AuraEnabled
public static List<Account> getAccountData(){
return [select Id,Name, AccountNumber from Account limit 50];
}
@AuraEnabled
public static List<Account> deleteAccount(String AccountId)
{
Account delAccount=[Select Id from Account where id=:AccountId];
delete delAccount;
return getAccountData();
}
}
Component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes"
access="global"
controller="AccountCtrl">
<aura:handler name="init" value="{!this}" action="{!c.doinit}"/>
<aura:attribute name="Acclist" type="list"/>
<div>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<thead>
<tr class="slds-line-height_reset">
<th class="slds-text-title_caps" scope="col">
<div class="slds-truncate" title="AccountId">Accoount Id</div>
</th>
<th class="slds-text-title_caps" scope="col">
<div class="slds-truncate" title="Account Name">Account Name</div>
</th>
<th class="slds-text-title_caps" scope="col">
<div class="slds-truncate" title="Account Number">Account Number</div>
</th>
<th class="slds-text-title_caps" scope="col">
<div class="slds-truncate" title="Delete">Delete</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.Acclist}" var="item" >
<tr class="slds-hint-parent">
<td data-label="Account Id">
<div class="slds-truncate" title="{!item.Id}">{!item.Id}</div>
</td>
<td data-label="Account Name">
<div class="slds-truncate" title="{!item.Name}">{!item.Name}</div>
</td>
<td data-label="icon" class="slds-col slds-size_1-of-12" onclick="{!c.delete}" id="{!item.Id}">
<lightning:button label="Delete" iconName="utility:delete" iconPosition="right" variant="destructive" />
</td>
</tr>
</aura:iteration>
</tbody>
</table>
</div>
</aura:component>
Controller
----------
({
doinit: function(component) {
var action = component.get('c.getAccountData');
var self = this;
action.setCallback(this, function(actionResult) {
component.set('v.Acclist', actionResult.getReturnValue());
});
$A.enqueueAction(action);
},
delete : function(component, event) {
var action = component.get("c.deleteAccount");
action.setParams({AccountId:event.target.id});
action.setCallback(this, function(response) {
component.set("v.Acclist",response.getReturnValue());
});
$A.enqueueAction(action);
}
})
******************** SOAP INTEGRATION ********************
16. SOAP Web service to create Account record.
global class CreateAccountWebService{
webservice static String createAcc(String accountName){
Account acc = new Account();
acc.Name = accountName;
insert acc;
return 'Account is created successfully. Account Id is: '+acc.Id;
}
}
Soap Inboud web service to create Account:
global class AccountCreationWebServiceUsingSoap {
global class AccountRequestDetails {
webservice String accountName;
webservice String accountDescription;
}
global class AccountResponseDetails {
webservice String accountCreationStatus;
webservice String accountName;
}
private static AccountResponseDetails requiredFieldValidation(AccountRequestDetails accountRequest) {
AccountResponseDetails accountResponse = new AccountResponseDetails();
if(accountRequest.accountDescription == NULL || accountRequest.accountDescription == '' ) {
accountResponse.accountCreationStatus = 'Please enter description';
}
return accountResponse;
}
private static AccountResponseDetails insertAccount(AccountRequestDetails accRequest) {
AccountResponseDetails accResponse = new AccountResponseDetails();
accResponse = requiredFieldValidation(accRequest);
if(accResponse.accountCreationStatus == NULL || accResponse.accountCreationStatus == '') {
Account acc = new Account();
acc.Name = accRequest.accountName;
acc.Description = accRequest.accountDescription;
try{
insert acc;
accResponse.accountCreationStatus = 'Account is created. Account Id is: '+acc.Id;
accResponse.accountName = acc.Name;
return accResponse;
}
catch(Exception e) {
String msg = 'Error occurred' +e.getMessage();
accResponse.accountCreationStatus = msg;
return accResponse;
}
}
return accResponse;
}
webservice static AccountResponseDetails createAccount(AccountRequestDetails accReq) {
AccountResponseDetails accResponse = insertAccount(accReq);
return accResponse;
}
}
Visualforce page and apex class for SOAP Outbound Account Creation:
public class SOAP_Outbound_Account_Creation {
public Account acc {get; set;}
public String destinationAccountStatus {get; set;}
public String sourceAccountStatus {get; set;}
public SOAP_Outbound_Account_Creation(){
acc = new Account();
destinationAccountStatus = '';
sourceAccountStatus = '';
}
public PageReference doSave(){
partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();
partnerSoapSforceCom.LoginResult log = sp.login('sohel@sf.com', 'so123');
soapSforceComSchemasClassAccountcre.SessionHeader_element SessionHeader =
new soapSforceComSchemasClassAccountcre.SessionHeader_element();
SessionHeader.sessionId = log.sessionId;
soapSforceComSchemasClassAccountcre.AccountCreationWebServiceUsingSoap AccountCreationWebService =
new soapSforceComSchemasClassAccountcre.AccountCreationWebServiceUsingSoap();
AccountCreationWebService.SessionHeader = SessionHeader;
soapSforceComSchemasClassAccountcre.AccountRequestDetails AccountRequest =
new soapSforceComSchemasClassAccountcre.AccountRequestDetails();
AccountRequest.accountName = acc.Name;
AccountRequest.accountDescription = acc.Description;
soapSforceComSchemasClassAccountcre.AccountResponseDetails response =
new soapSforceComSchemasClassAccountcre.AccountResponseDetails();
response = AccountCreationWebService.createAccount(AccountRequest);
insert acc;
sourceAccountStatus = 'Source Org: Account is created. Account Id: '+acc.Id;
destinationAccountStatus = 'Destination Org: '+response.accountCreationStatus;
return null;
}
}
<apex:page controller="SOAP_Outbound_Account_Creation">
<apex:sectionHeader title="Create" subtitle="Account"/>
<apex:form >
<apex:outputText value="{!sourceAccountStatus }" style="color:green; font-weighte:bold;"/><br/><br/>
<apex:outputText value="{!destinationAccountStatus }" style="color:green; font-weighte:bold;" />
<apex:pageBlock title="Account Info">
<apex:pageBlockSection >
<apex:inputField value="{!acc.Name}"/>
<apex:inputField value="{!acc.Description}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!doSave}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
Result:
Source Org: Account is created. Account Id: 0010I00002JiL1TQAV
Destination Org: Account is created. Account Id is: 0010K00002DQTBwQAP
16. SOAP Web service to create Account record.
global class CreateAccountWebService{
webservice static String createAcc(String accountName){
Account acc = new Account();
acc.Name = accountName;
insert acc;
return 'Account is created successfully. Account Id is: '+acc.Id;
}
}
Soap Inboud web service to create Account:
global class AccountCreationWebServiceUsingSoap {
global class AccountRequestDetails {
webservice String accountName;
webservice String accountDescription;
}
global class AccountResponseDetails {
webservice String accountCreationStatus;
webservice String accountName;
}
private static AccountResponseDetails requiredFieldValidation(AccountRequestDetails accountRequest) {
AccountResponseDetails accountResponse = new AccountResponseDetails();
if(accountRequest.accountDescription == NULL || accountRequest.accountDescription == '' ) {
accountResponse.accountCreationStatus = 'Please enter description';
}
return accountResponse;
}
private static AccountResponseDetails insertAccount(AccountRequestDetails accRequest) {
AccountResponseDetails accResponse = new AccountResponseDetails();
accResponse = requiredFieldValidation(accRequest);
if(accResponse.accountCreationStatus == NULL || accResponse.accountCreationStatus == '') {
Account acc = new Account();
acc.Name = accRequest.accountName;
acc.Description = accRequest.accountDescription;
try{
insert acc;
accResponse.accountCreationStatus = 'Account is created. Account Id is: '+acc.Id;
accResponse.accountName = acc.Name;
return accResponse;
}
catch(Exception e) {
String msg = 'Error occurred' +e.getMessage();
accResponse.accountCreationStatus = msg;
return accResponse;
}
}
return accResponse;
}
webservice static AccountResponseDetails createAccount(AccountRequestDetails accReq) {
AccountResponseDetails accResponse = insertAccount(accReq);
return accResponse;
}
}
Visualforce page and apex class for SOAP Outbound Account Creation:
public class SOAP_Outbound_Account_Creation {
public Account acc {get; set;}
public String destinationAccountStatus {get; set;}
public String sourceAccountStatus {get; set;}
public SOAP_Outbound_Account_Creation(){
acc = new Account();
destinationAccountStatus = '';
sourceAccountStatus = '';
}
public PageReference doSave(){
partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();
partnerSoapSforceCom.LoginResult log = sp.login('sohel@sf.com', 'so123');
soapSforceComSchemasClassAccountcre.SessionHeader_element SessionHeader =
new soapSforceComSchemasClassAccountcre.SessionHeader_element();
SessionHeader.sessionId = log.sessionId;
soapSforceComSchemasClassAccountcre.AccountCreationWebServiceUsingSoap AccountCreationWebService =
new soapSforceComSchemasClassAccountcre.AccountCreationWebServiceUsingSoap();
AccountCreationWebService.SessionHeader = SessionHeader;
soapSforceComSchemasClassAccountcre.AccountRequestDetails AccountRequest =
new soapSforceComSchemasClassAccountcre.AccountRequestDetails();
AccountRequest.accountName = acc.Name;
AccountRequest.accountDescription = acc.Description;
soapSforceComSchemasClassAccountcre.AccountResponseDetails response =
new soapSforceComSchemasClassAccountcre.AccountResponseDetails();
response = AccountCreationWebService.createAccount(AccountRequest);
insert acc;
sourceAccountStatus = 'Source Org: Account is created. Account Id: '+acc.Id;
destinationAccountStatus = 'Destination Org: '+response.accountCreationStatus;
return null;
}
}
<apex:page controller="SOAP_Outbound_Account_Creation">
<apex:sectionHeader title="Create" subtitle="Account"/>
<apex:form >
<apex:outputText value="{!sourceAccountStatus }" style="color:green; font-weighte:bold;"/><br/><br/>
<apex:outputText value="{!destinationAccountStatus }" style="color:green; font-weighte:bold;" />
<apex:pageBlock title="Account Info">
<apex:pageBlockSection >
<apex:inputField value="{!acc.Name}"/>
<apex:inputField value="{!acc.Description}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!doSave}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
Result:
Source Org: Account is created. Account Id: 0010I00002JiL1TQAV
Destination Org: Account is created. Account Id is: 0010K00002DQTBwQAP
===============================================
17. Rest Inbound web service to create record.
/*************
Workbench rest post url: /services/apexrest/ ContactCreationRestservice2
Request Body:
{
"req": {
"contactLastName" : "Test",
"contactEmail" : "test@test.com",
"contactPhone" : "1212121212"
}
}
***************
@RestResource(urlMapping='/ContactCreationRestservice2/*')
global class ContactCreationRestservice2{
global class ContactRequestDetails{
webservice String contactLastName;
webservice String contactEmail;
webservice String contactPhone;
}
global class ContactResponseDetails{
webservice String contactLastName;
webservice String contactCreationStatus;
webservice String errorMessageStatus;
}
private static ContactResponseDetails validateRequiredFields(ContactRequestDetails contactRequest){
ContactResponseDetails contactResponse = new ContactResponseDetails();
if(contactRequest.contactPhone == '' || contactRequest.contactPhone == NULL){
contactResponse.contactCreationStatus = 'Please enter Phone Number';
}
return contactResponse;
}
private static ContactResponseDetails insertContactDetails(ContactRequestDetails contRequest){
ContactResponseDetails contResp = new ContactResponseDetails();
contResp = validateRequiredFields(contRequest);
if(contResp.contactCreationStatus == NULL || contResp.contactCreationStatus == ''){
Contact contactObject = new Contact();
contactObject.LastName = contRequest.contactLastName;
contactObject.Email = contRequest.contactEmail;
contactObject.Phone = contRequest.contactPhone;
try
{
insert contactObject;
contResp.contactCreationStatus = 'Contact is created successfully. Contact Id: ' +contactObject.Id;
contResp.contactLastName = contactObject.LastName;
return contResp;
}
catch(Exception ex){
String errorMessage = 'Error occurred' +ex.getMessage();
contResp.contactCreationStatus = errorMessage;
return contResp;
}
}
else{
return contResp;
}
}
@HttpPost
global static ContactResponseDetails createContact(ContactRequestDetails req){
//RestRequest restReq = RestContext.request;
//RestResponse restResp = RestContext.response;
ContactResponseDetails res = insertContactDetails(req);
return res;
}
}
Rest Outbound web service for above inbound rest service:
===================================
public class ContactCreationRestservice_Outbound{
public String contactPhone { get; set; }
public String contactEmail { get; set; }
public String contactLastName { get; set; }
public String contReq { get; set; }
public String response{get;set;}
public class ContactRequestDetails{
String contactLastName;
String contactEmail;
String contactPhone;
}
public PageReference CreateContact() {
ContactRequestDetails contReq = new ContactRequestDetails();
//find access token using Auth 2.0
String Access_Token='00D28000000JPGf!AQ8AQJH27ODTW8k4SQz1wd5zKMXKX7D7tGwmjkyETuNjdwgl94yIeBN8QFpVlRQg_xQWeEpBjhtKjWVurcU.EQUP0ND3Jovp';
//String username = 'sohel@sf.com';
//String password = 'so123';
Httprequest req=new httprequest();
String domainName= 'https://mohd-sohel-dev-ed.my.salesforce.com';
String endPointURL='https://mohd-sohel-dev-ed.my.salesforce.com/services/apexrest/ContactCreationRestservice2/';
//String endPointURL='https://mohd-sohel-dev-ed.my.salesforce.com/services/data/v27.0/sobjects/Account';
req.setendpoint(endPointURL);
req.setHeader('Content-Type', 'application/xml; charset=utf-8');
req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+contactLastName+'</name><email>'+contactEmail+'</email><phone>'+contactPhone+'</phone> </request>');
req.setmethod('POST');
//Blob headerValue = Blob.valueOf(username + ':' + password);
//String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
//req.setHeader('Authorization', authorizationHeader);
req.setHeader('Authorization','Authorization: Bearer '+Access_Token);
Http http = new Http();
HTTPResponse res = http.send(req);
response=res.getbody();
System.debug('****************res.getStatusCode();'+res.getStatusCode());
System.debug('****************res.getbody();'+res.getbody());
return null;
}
}
Visualforce page:
<apex:page controller="ContactCreationRestservice_Outbound">
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton value="Create Contact in SF1 instance" action="{!CreateContact}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel for="aname" value="Name"></apex:outputLabel>
<apex:inputText value="{!contactLastName}" id="aname"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel for="aphone" value="email"></apex:outputLabel>
<apex:inputText value="{!contactEmail}" id="aphone"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel for="aw" value="Phone"></apex:outputLabel>
<apex:inputText value="{!contactPhone}" id="aw"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock title="Response">
<apex:pageBlockSection >
<apex:outputText value="{!Response}"></apex:outputText>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
/*************
Workbench rest post url: /services/apexrest/ ContactCreationRestservice2
Request Body:
{
"req": {
"contactLastName" : "Test",
"contactEmail" : "test@test.com",
"contactPhone" : "1212121212"
}
}
***************
@RestResource(urlMapping='/ContactCreationRestservice2/*')
global class ContactCreationRestservice2{
global class ContactRequestDetails{
webservice String contactLastName;
webservice String contactEmail;
webservice String contactPhone;
}
global class ContactResponseDetails{
webservice String contactLastName;
webservice String contactCreationStatus;
webservice String errorMessageStatus;
}
private static ContactResponseDetails validateRequiredFields(ContactRequestDetails contactRequest){
ContactResponseDetails contactResponse = new ContactResponseDetails();
if(contactRequest.contactPhone == '' || contactRequest.contactPhone == NULL){
contactResponse.contactCreationStatus = 'Please enter Phone Number';
}
return contactResponse;
}
private static ContactResponseDetails insertContactDetails(ContactRequestDetails contRequest){
ContactResponseDetails contResp = new ContactResponseDetails();
contResp = validateRequiredFields(contRequest);
if(contResp.contactCreationStatus == NULL || contResp.contactCreationStatus == ''){
Contact contactObject = new Contact();
contactObject.LastName = contRequest.contactLastName;
contactObject.Email = contRequest.contactEmail;
contactObject.Phone = contRequest.contactPhone;
try
{
insert contactObject;
contResp.contactCreationStatus = 'Contact is created successfully. Contact Id: ' +contactObject.Id;
contResp.contactLastName = contactObject.LastName;
return contResp;
}
catch(Exception ex){
String errorMessage = 'Error occurred' +ex.getMessage();
contResp.contactCreationStatus = errorMessage;
return contResp;
}
}
else{
return contResp;
}
}
@HttpPost
global static ContactResponseDetails createContact(ContactRequestDetails req){
//RestRequest restReq = RestContext.request;
//RestResponse restResp = RestContext.response;
ContactResponseDetails res = insertContactDetails(req);
return res;
}
}
Rest Outbound web service for above inbound rest service:
===================================
public class ContactCreationRestservice_Outbound{
public String contactPhone { get; set; }
public String contactEmail { get; set; }
public String contactLastName { get; set; }
public String contReq { get; set; }
public String response{get;set;}
public class ContactRequestDetails{
String contactLastName;
String contactEmail;
String contactPhone;
}
public PageReference CreateContact() {
ContactRequestDetails contReq = new ContactRequestDetails();
//find access token using Auth 2.0
String Access_Token='00D28000000JPGf!AQ8AQJH27ODTW8k4SQz1wd5zKMXKX7D7tGwmjkyETuNjdwgl94yIeBN8QFpVlRQg_xQWeEpBjhtKjWVurcU.EQUP0ND3Jovp';
//String username = 'sohel@sf.com';
//String password = 'so123';
Httprequest req=new httprequest();
String domainName= 'https://mohd-sohel-dev-ed.my.salesforce.com';
String endPointURL='https://mohd-sohel-dev-ed.my.salesforce.com/services/apexrest/ContactCreationRestservice2/';
//String endPointURL='https://mohd-sohel-dev-ed.my.salesforce.com/services/data/v27.0/sobjects/Account';
req.setendpoint(endPointURL);
req.setHeader('Content-Type', 'application/xml; charset=utf-8');
req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+contactLastName+'</name><email>'+contactEmail+'</email><phone>'+contactPhone+'</phone> </request>');
req.setmethod('POST');
//Blob headerValue = Blob.valueOf(username + ':' + password);
//String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
//req.setHeader('Authorization', authorizationHeader);
req.setHeader('Authorization','Authorization: Bearer '+Access_Token);
Http http = new Http();
HTTPResponse res = http.send(req);
response=res.getbody();
System.debug('****************res.getStatusCode();'+res.getStatusCode());
System.debug('****************res.getbody();'+res.getbody());
return null;
}
}
Visualforce page:
<apex:page controller="ContactCreationRestservice_Outbound">
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton value="Create Contact in SF1 instance" action="{!CreateContact}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel for="aname" value="Name"></apex:outputLabel>
<apex:inputText value="{!contactLastName}" id="aname"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel for="aphone" value="email"></apex:outputLabel>
<apex:inputText value="{!contactEmail}" id="aphone"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel for="aw" value="Phone"></apex:outputLabel>
<apex:inputText value="{!contactPhone}" id="aw"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock title="Response">
<apex:pageBlockSection >
<apex:outputText value="{!Response}"></apex:outputText>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
18. Aura Applicatio & Component events:
COMPONENT EVENT –
Component events are handled by the same component that fires the event or by the component that contains the component that fire the event
APPLICATION EVENT –
Application events are handled by those who are listening to the Application event. These events are based on the publish-subscribe model.
EXAMPLE OF THE COMPONENT EVENT –
Usecase: When a user in the child component click on a button message need to be set in the component event and fire the event by the same component and handled over the Parent component
Component Event –
<!-- EXAMPLE OF THE COMPONENT EVENT -->
<aura:event type="COMPONENT">
<aura:attribute name="msg" type="String"/>
</aura:event>
Child Component –
<!-- CHILD COMPONENT -->
<aura:component>
<aura:registerEvent name="cmpoEvent" type="c:ceEvent"/>
<h1>Component Event Example</h1>
<p><lightning:button
label="Fire Component Event"
onclick="{!c.fireNow}" />
</p>
</aura:component>
Child Controller –
{
fireNow : function(component, event) {
// Get the component event by using the
// name value from aura:registerEvent
var compEvent =
component.getEvent("cmpoEvent");
compEvent.setParams({
"message": "I am setting message
from the child component to the parent
component by the help of a component and
this is my Component event example" });
compEvent.fire();
}
}
Parent Component –
<!-- PARENT COMPONENT -->
<aura:component>
<aura:attribute name="messageFromChildEvent" type="String"/>
<aura:attribute name="numOfEvents" type="Integer" default="0"/>
<!-- Note that name="cmpEvent" in aura:registerEvent
in ceNotifier.cmp -->
<aura:handler name="cmpEvent" event="c:ceEvent" action="{!c.handleCE}"/>
<!-- handler contains the notifier component -->
<c:childComponent/>
<p>{!v.messageFromChildEvent}</p>
<p>Number of events: {!v.numOfEvents}</p>
</aura:component>
Parent Controller
{
handleCE : function(component, event) {
var message = event.getParam("msg");
// set the handler attributes based on event data
component.set("v.messageFromChildEvent", message);
var numEventsHandled = parseInt(component.get("v.numOfEvents")) + 1;
component.set("v.numEvents", numEventsHandled);
}
}
To test this out you need to place your parent component in a lightning application and test it out
<aura:application extends=”force:slds” >
<c:ParentComponent/>
</aura:application>
EXAMPLE OF THE APPLICATION EVENT –
Usecase: Event is fired by Component A and Handled by Component B
Application Event ( aEvent )
<!-- EXAMPLE OF THE APPLICATION EVENT -->
<aura:event type="APPLICATION">
<aura:attribute name="msg" type="String"/>
</aura:event>
Component A
<aura:component>
<aura:registerEvent name="appEvent" type="c:aEvent"/>
<h1>EXAMPLE OF THE APPLICATION EVENT</h1>
<p><lightning:button
label="Click Now for Firing the Application Event"
onclick="{!c.fireEvent}" />
</p>
</aura:component>
Controller A
{
fireApplicationEvent : function(component, event) {
var apEvent = $A.get("e.c:aEvent");
apEvent.setParams({
"message" : "I’M FIRING THE EVENT AND
SET A MESSAGE FROM ONE COMPOENT TO ANOTHER
hEY hOW ARE YOU WELCOME TO SALESFORCE SKY" });
apEvent.fire();
}
}
Component B
<aura:component>
<aura:attribute name="messageEvent" type="String"/>
<aura:attribute name="numOFEvents" type="Integer" default="0"/>
<aura:handler event="c:aEvent" action="{!c.handleAppEvent}"/>
<p>{!v.messageEvent}</p>
<p>Number of events: {!v.numOFEvents}</p>
</aura:component>
Controller B
{
handleAppEvent : function(component, event) {
var message = event.getParam("msg");
// set the handler attributes based on event data
component.set("v.messageEvent", message);
var numEventsHandled = parseInt(component.get("v.numOFEvents")) + 1;
component.set("v.numOFEvents", numEventsHandled);
}
}
Now put both the component in a parent component
<!--Parent Component-->
<aura:component>
<c:A/>
<c:B/>
</aura:component>
Place your Parent Component in a Lightning App to Test it Out
<aura:application extends=”force:slds” >
<c:ParentComponent/>
</aura:application>
STANDARD EVENTS –
Standard events are the ones that are by default came with the framework, so we don’t need to create them we can use them on our own. Like init, show toast etc
19. Dynamic search functionality in Lightning Web Component with event:
public with sharing class AccountDataController {
public AccountDataController() {
}
@AuraEnabled
public static List<Account> displayAccounts(String searchekey){
String searchword='%'+searchekey+'%';
List<Account> returnlist=new List<Account>();
if(!String.isBlank(searchekey))
for(Account acc:[select Id,Name,Site from Account where Name like:searchword]){
returnlist.add(acc);
}
return returnlist;
}
}
searchAccountComponent.html
<template>
<lightning-input type="text" class="accName" label="SearchAccounts" onchange={handleSearch}>
</lightning-input>
</template>
searchAccountComponent.js
import { LightningElement,api } from 'lwc';
export default class SearchAccountComponent extends LightningElement {
@api userInput;
handleSearch(event){
this.userInput=event.target.value;
const newEvent=new CustomEvent('inputcarryevent',{
detail:this.userInput
});
this.dispatchEvent(newEvent);
}
}
accountDataComponent.html
<template>
<c-search-account-component oninputcarryevent={displayData}>
</c-search-account-component><br/><br/>
<div if:true={isshow}>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td><b>Name</b></td>
<td><b>Site</b></td>
</tr>
<template for:each={records} for:item="acc">
<tr key={acc.Id}>
<td>
{acc.Name}
</td>
<td>
{acc.Site}
</td>
</tr>
</template>
</table>
</div>
</template>
accountDataComponent.js
import { LightningElement,api } from 'lwc';
import displayAccounts from '@salesforce/apex/AccountDataController.displayAccounts';
export default class AccountDataComponent extends LightningElement {
@api records;
@api error;
@api isshow;
displayData(event){
console.log('@@@@Entered into the method@@@');
displayAccounts({
searchekey:event.detail
})
.then(result=>{
this.records=result;
console.log('@@@records'+JSON.stringify(this.records));
if(result.length!=0){
this.isshow=true;
}
else{
this.isshow=false;
}
this.error=undefined;
})
.catch(error=>{
this.records=undefined;
this.error=error;
});
}
}
LightningApplication
<aura:application extends="force:slds" >
<c:accountDataComponent/>
</aura:application>
20. REST Inbound Web service with all types of methods:
@RestResource(urlMapping='/Cases/*')
global with sharing class CaseManager {
@HttpGet
global static Case getCaseById() {
RestRequest request = RestContext.request;
String caseId = request.requestURI.substring(
request.requestURI.lastIndexOf('/')+1);
Case result = [SELECT CaseNumber,Subject,Status,Origin,Priority
FROM Case
WHERE Id = :caseId];
return result;
}
@HttpPost
global static ID createCase(String subject, String status,
String origin, String priority) {
Case thisCase = new Case(
Subject=subject,
Status=status,
Origin=origin,
Priority=priority);
insert thisCase;
return thisCase.Id;
}
@HttpDelete
global static void deleteCase() {
RestRequest request = RestContext.request;
String caseId = request.requestURI.substring(
request.requestURI.lastIndexOf('/')+1);
Case thisCase = [SELECT Id FROM Case WHERE Id = :caseId];
delete thisCase;
}
@HttpPut
global static ID upsertCase(String subject, String status,
String origin, String priority, String id) {
Case thisCase = new Case(
Id=id,
Subject=subject,
Status=status,
Origin=origin,
Priority=priority);
upsert thisCase;
return thisCase.Id;
}
@HttpPatch
global static ID updateCaseFields() {
RestRequest request = RestContext.request;
String caseId = request.requestURI.substring(
request.requestURI.lastIndexOf('/')+1);
Case thisCase = [SELECT Id FROM Case WHERE Id = :caseId];
// Deserialize the JSON string into name-value pairs
Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());
// Iterate through each parameter field and value
for(String fieldName : params.keySet()) {
// Set the field and value on the Case sObject
thisCase.put(fieldName, params.get(fieldName));
}
update thisCase;
return thisCase.Id;
}
}
global with sharing class CaseManager {
@HttpGet
global static Case getCaseById() {
RestRequest request = RestContext.request;
String caseId = request.requestURI.substring(
request.requestURI.lastIndexOf('/')+1);
Case result = [SELECT CaseNumber,Subject,Status,Origin,Priority
FROM Case
WHERE Id = :caseId];
return result;
}
@HttpPost
global static ID createCase(String subject, String status,
String origin, String priority) {
Case thisCase = new Case(
Subject=subject,
Status=status,
Origin=origin,
Priority=priority);
insert thisCase;
return thisCase.Id;
}
@HttpDelete
global static void deleteCase() {
RestRequest request = RestContext.request;
String caseId = request.requestURI.substring(
request.requestURI.lastIndexOf('/')+1);
Case thisCase = [SELECT Id FROM Case WHERE Id = :caseId];
delete thisCase;
}
@HttpPut
global static ID upsertCase(String subject, String status,
String origin, String priority, String id) {
Case thisCase = new Case(
Id=id,
Subject=subject,
Status=status,
Origin=origin,
Priority=priority);
upsert thisCase;
return thisCase.Id;
}
@HttpPatch
global static ID updateCaseFields() {
RestRequest request = RestContext.request;
String caseId = request.requestURI.substring(
request.requestURI.lastIndexOf('/')+1);
Case thisCase = [SELECT Id FROM Case WHERE Id = :caseId];
// Deserialize the JSON string into name-value pairs
Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());
// Iterate through each parameter field and value
for(String fieldName : params.keySet()) {
// Set the field and value on the Case sObject
thisCase.put(fieldName, params.get(fieldName));
}
update thisCase;
return thisCase.Id;
}
}
No comments:
Post a Comment