Salesforce Interview Preparation:
Similarly if you've list of Accounts
in your JSON then try like this:
[
{
"Name":"ABC",
"AccountNumber":"1312321"
},
{
"Name":"DEF",
"AccountNumber":"456456"
}
]
Apex code for list of Accounts:
String jsonString = '[{"Name":"ABC","AccountNumber":"1312321"},{"Name":"DEF","AccountNumber":"456456"}]';
List<Account> actList = (List<Account>) JSON.deserialize(jsonString, List<Account>.class);
System.debug('Count:'+actList.size());
Apex Class:
public class CustomClass {
public Integer price;
public date startDate;
public date endDate;
public String name;
public String category;
}
Deserialize JSON:
String jsonString = '{"price":100,"startDate":"09-09-2009","endDate":"09-10-2009","name":"IPHONE","category":"Mobile"}';
CustomClass obj = (CustomClass) JSON.deserialize(jsonString, CustomClass.class);
System.debug('CustomClass:'+obj.name);
XML Parsing: Parse XML response and store it in Account object and create Account records with XML received from workbench.
@RestResource(urlMapping = '/AccountXMLService/*')
global class AccountXmlParser {
@HttpPost
global static void parse(){
List<Account> accounts = new List<Account>();
String xml = RestContext.request.requestBody.toString();
System.debug('xml received '+xml);
Dom.Document doc = new Dom.Document();
doc.load(xml);
Dom.XmlNode root = doc.getRootElement();
for(Dom.XmlNode accountNode: root.getChildElements()){
Account account = new Account();
for(Dom.XmlNode fieldNode: accountNode.getChildElements()){
String fieldName = fieldNode.getName();
String fieldValue = fieldNode.getText();
if(fieldName == 'Id'){
account.Id = fieldName;
}
else if(fieldName == 'Name'){
account.Name = fieldValue;
}
else if(fieldName == 'Type'){
account.Type = fieldValue;
}
}
accounts.add(account);
}
insert accounts;
System.debug('accounts '+accounts);
}
}
/*
execute below xml from workbench ==> Rest explorer ==>Post ==> Request Body
/services/apexrest/AccountXMLService/*
<Accounts>
<Account>
<Name>Acc1-XML</Name>
<Type>Customer - Channel</Type>
<Industry>Manufacturing</Industry>
</Account>
<Account>
<Name>Acc2-XML</Name>
<Type>Prospect</Type>
<Industry>Retail</Industry>
</Account>
</Accounts>
*/
Then in your apex trigger, add an IF condition at the top to check if the Trigger status in Custom settings is TRUE, only then run the entire apex trigger code.
trigger oppTrigger on opportunity (before insert){ Trigger_Settings__c TS = Trigger_Settings__c.getValues('oppTrigger'); if(TS.is_Active__c == TRUE){ //your trigger code } }
Salesforce.com >> Using a validation rule, how to allow specific user to create a new record on Account and restrict other user?
A nice way to do this is to use custom permissions. With this you can create your very own permissions that can be added to profiles or permission sets. You can then insert a check for this permission in the validation rule itself.
For example, if you created a custom permission "Bypass Validation X" ("X" representing the meaning of the validation to be bypassed) you can add that to profiles or permission sets and do something like the following in your validation rule:
NOT($Permission.Bypass_Validation_X) AND (...)
Where "..." is the original validation rule content without any user ID checking parts.
Only users with the required custom permission will be able to bypass the validation.
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();
public class sampleFutureClass {
@future
public static void methodName(List<Id> accountIds){
// logic
}
}
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.
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;
}
}
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;
}
}
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.
global class sampleRestClass {
@HttpPost
global static Account createAccount(String accName){
Account acc = new Account(Name = accName);
insert acc;
return acc;
}
}
9. Lightning Web Component: is used to create UI for Salesforce applications.
LWC to display records:
Server Side Controller:
Continuation:
public with sharing class ContinuationSampleController {
//Action method
@AuraEnabled(continuation=true)
public static Object sendRequest() {
Continuation con = new Continuation(40);
con.continuationMethod='getResponse';
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('CALLOUT_URL');
con.addHttpRequest(req);
con.state='This is state from request method';
return con;
}
// Callback method
@AuraEnabled
public static Object getResponse(List<String> labels, Object state) {
HttpResponse response = Continuation.getResponse(labels[0]);
String result = response.getBody();
return result;
}
}
Here’s the component’s JavaScript file.
import { LightningElement, track } from 'lwc';
import sendRequest from '@salesforce/apexContinuation/ContinuationSampleController.sendRequest ';
export default class ContinuationSample extends LightningElement {
@track listOfRecords={};
@track error;
connectedCallback() {
sendRequest()
.then(result => {
this.listOfRecords = result;
this.error = undefined;
})
.catch(error => {
this.error = error;
this.listOfRecords = undefined;
});
}
}
HTML Code
<!-- ContinuationSample.html -->
<template>
<div>
Show result: {listOfRecords}
</div>
</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));
});
}
}
14. 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
/*************
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>
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;
}
}
trigger ContactUpdate on Account(after update) {
Map < Id, Account > mapAccount = new Map < Id, Account > ();
List < Contact > listContact = new List < Contact > ();
for (Account acct: trigger.new)
mapAccount.put(acct.Id, acct);
listContact = [SELECT MailingStreet, MailingCity, AccountId FROM Contact
WHERE AccountId IN: mapAccount.keySet()
];
if (listContact.size() > 0) {
for (Contact con: listContact) {
con.MailingStreet = mapAccount.get(con.AccountId).BillingStreet;
con.MailingCity = mapAccount.get(con.AccountId).BillingCity;
}
update listContact;
}
}
19. Apex trigger to update parent record when child record is updated.
Trigger UpdateDescription on Contact(after insert, after update) {
Map < ID, Account > accIdMap = new Map < ID, Account > ();
//Making it a map instead of list for easier lookup
List < Id > accIdSet = new List < Id > ();
for (Contact childObj: Trigger.new {
accIdSet.add(childObj.AccountId);
}
accIdMap = new Map < Id, Account > ([SELECT id, Description,
(SELECT ID, Description FROM Contacts) FROM Account WHERE ID IN: accIdSet
]);
for (Contact con: Trigger: new) {
Account myParentOpp = accIdMap.get(con.AccountId);
myParentOpp.Description = con.Description;
}
update accIdMap.values();
}
22. Trigger to count, sum, min, max, avg of child records using Aggregate Result:
24. Apex trigger to prevent duplicate Account records.
Trigger preventDuplicateAccount(before insert, before update) {
Set < String > setAccountNames = new Set < String > ();
Map < String, Account > mapAccount = new Map < String, Account > ();
for (Account acc: Trigger.new) {
setAccountNames.add(acc.Name);
}
for (Account acc: [SELECT Id, Name FROM Account
WHERE Name IN: setAccountNames]) {
mapAccount.put(acc.Name, acc);
}
for (Account acc: Trigger.new) {
if (mapAccount.containsKey(acc.Name)) {
acc.Name.addError('Account name already exists for Account id ' + mapAccount.get(acc.Name) + '.');
}
}
}
Set<String> accountNameSet = new Set<String>();
for(Account acc: [SELECT Name FROM Account]){
accountNameSet.add(acc.Name);
System.debug('accountNameSet @@ '+accountNameSet);
}
for(Account acc: Trigger.new){
if(accountNameSet.contains(acc.Name)){
System.debug('accountNameSet.contains(acc.Name) '+acc.Name);
acc.Name.addError('An Account exists with same name ! ');
}
}
}
25. Trigger to count, sum child records and display in parent record
in case of lookup relationship.
Trigger ContactCountTrigger on Contact(After insert, After Delete, After Undelete, After Update) {
Set < Id > setAccountIds = new Set < Id > ();
if (Trigger.isInsert || Trigger.isUndelete || Trigger.IsUpdate) {
for (Contact con: Trigger.new) {
setAccountIds.add(con.AccountId);
}
}
if (Trigger.isDelete) {
for (Contact con: Trigger.old) {
setAccountIds.add(con.AccountId);
}
}
List < Account > listAccs = [Select id, name, number_of_contacts__c,
(Select id from contacts) from Account
where Id in: setAccountIds
];
for (Account acc: listAccs) {
acc.number_of_contacts__c =
acc.contacts.size();
}
update listAccs;
}
=================================================================
====================================
<address>
<name>Kirk Stevens</name>
<street1>808 State St</street1>
<street2>Apt. 2</street2>
<city>Palookaville</city>
<state>PA</state>
<country>USA</country>
</address>
The following example illustrates how to use DOM classes to parse the XML response returned in the body of a GET request.
public class DomDocument {
// Pass in the URL for the request
// For the purposes of this sample,assume that the URL
// returns the XML shown above in the response body
public void parseResponseDom(String url){
Http h = new Http();
HttpRequest req = new HttpRequest();
// url that returns the XML in the response body
req.setEndpoint(url);
req.setMethod('GET');
HttpResponse res = h.send(req);
Dom.Document doc = res.getBodyDocument();
//Retrieve the root element for this document.
Dom.XMLNode address = doc.getRootElement();
String name = address.getChildElement('name', null).getText();
String state = address.getChildElement('state', null).getText();
// print out specific elements
System.debug('Name: ' + name);
System.debug('State: ' + state);
// Alternatively, loop through the child elements.
// This prints out all the elements of the address
for(Dom.XMLNode child : address.getChildElements()) {
System.debug(child.getText());
}
}
}
=======================================================================================================
trigger AccountTrigger on Account (before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
Boolean run = true;
if(run == false){
if(Trigger.isBefore){
if(Trigger.isInsert) {
AccountTriggerHandler.beforeInsert(Trigger.new);
}
if(Trigger.isUpdate){
AccountTriggerHandler.beforeUpdate(Trigger.new);
}
if(Trigger.isDelete){
AccountTriggerHandler.beforeDelete(Trigger.old);
}
}
if(Trigger.isAfter){
if(Trigger.isInsert){
AccountTriggerHandler.afterInsert(Trigger.new);
}
if(Trigger.isUpdate){
AccountTriggerHandler.afterUpdate(Trigger.new);
}
if(Trigger.isDelete){
AccountTriggerHandler.afterDelete(Trigger.old);
}
if(Trigger.isUndelete){
AccountTriggerHandler.afterUndelete(Trigger.new);
}
}
}
}
==============================================================
public class AccountTriggerHandler {
//Update Account Description when Account is created.
public static void beforeInsert(List<Account> newAccounts) {
for(Account acc: newAccounts){
acc.Description = 'Test Description';
}
}
//Update Account Rating based on Account Industry
public static void beforeUpdate(List<Account> newAccounts) {
for(Account acc: newAccounts){
if(String.isNotBlank(acc.Industry)){
if(acc.Industry == 'Banking'){
acc.Rating = 'Hot';
}
else if(acc.Industry == 'Agriculture'){
acc.Rating = 'Warm';
}
else {
acc.Rating = 'Cold';
}
}
}
}
// Restrict the deletion of Account if Industry = 'Banking'.
public static void beforeDelete(List<Account> oldAccs) {
for(Account acc: oldAccs){
if(String.isNotBlank(acc.Industry) && acc.Industry == 'Banking'){
acc.addError('Account cannot be deleted if Industry is Banking.');
}
}
}
//Create Contact record when Account is created.
public static void afterInsert(List<Account> newAccounts) {
List<Contact> listContact = new List<Contact>();
for(Account acc: newAccounts){
Contact con = new Contact();
con.LastName = acc.Name + ' Contact';
con.AccountId = acc.Id;
listContact.add(con);
}
if(!listContact.isEmpty()){
try{
Database.insert(listContact, false);
}
catch(Exception e){
System.debug('Exception '+e);
}
}
}
//Update Contact record when Account is updated.
public static void afterUpdate(List<Account> newAccounts) {
Map <Id, Account> mapAccount = new Map <Id, Account>();
List <Contact> listContact = new List <Contact>();
for (Account acct: newAccounts){
mapAccount.put(acct.Id, acct);
}
listContact = [SELECT Description, AccountId FROM Contact
WHERE AccountId IN: mapAccount.keySet()];
if (listContact.size() > 0) {
for (Contact con: listContact) {
con.Description = mapAccount.get(con.AccountId).Description;
}
update listContact;
}
}
//Send email notification when Account is deleted.
public static void afterDelete(List<Account> oldAccounts) {
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for (Account acc : oldAccounts) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'sohelsalesforcetraining@gmail.com'};
mail.setToAddresses(toAddresses);
mail.setSubject('Your Account is deleted');
String body = 'Your Account is deleted successfully from Salesforce org.';
mail.setHtmlBody(body);
mails.add(mail);
}
Messaging.sendEmail(mails);
}
// Update Account Name when Account is undeleted/restored.
public static void afterUndelete(List<Account> newAccounts) {
List<Account> listAccount = new List<Account>();
for(Account acc : [SELECT ID, Name, Description from Account where Id IN : newAccounts]){
acc.Name = acc.Name + ' - Undeleted';
acc.Description = 'This Account is undeleted by Apex Trigger';
listAccount.add(acc);
}
update listAccount;
}
}
=============================================
Trigger ContactTrigger on Contact(after , after update, after delete, after undelete){
Boolean maxContact = false;
List<CustomRecord__c> crList = new List<CustomRecord__c>();
List<Account> accList = new List<Account>();
Set<Id> accountIdSet = new Set<Id>();
if(Trigger.isAfter){
if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){
for(Contact con: Trigger.new){
if(con.AccountId != NULL){
accountIdSet.add(con.AccountId);
}
}
}
if(Trigger.isDelete){
for(Contact con: Trigger.old){
if(con.AccountId != NULL){
accountIdSet.add(con.AccountId);
}
}
}
}
accList = [SELECT Id, CountOfCOntacts__c, (SELECT Id FROM Contacts) FROM Account WHERE AccountId IN: accountIdSet];
if(!accList.isEmpty()){
for(Account acc: accList){
acc.CountOfCOntacts__c = acc.contacts.size();
if(acc.contacts.size() >='100'){
maxContact = true;
}
}
}
if(maxContact != TRUE){
if(!accList.isEmpty()){
try {
Database.update(accList, false);
}
catch(Exception ex){
System.debug('Exception '+ex.getMessage());
}
}
}
else {
for(Contact con: Trigger.new ){
CustomRecord__c c = new CustomRecord__c;
c.Account__c = con.AccountId;
c.Contact__c = con.Id;
crList.add(c);
}
insert crList;
}
}
No comments:
Post a Comment