public class MasterTrigger {
/*
******************** TRIGGERS ********************
1. 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);
}
}
}
2. 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');
}
}
}
}
3. 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 ! ');
}
}
}
4. 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;
}
5. Trigger to delete/undelete child records when parent records are deleted/undeleted.
trigger DeleteContacts on Account(after delete) {
List < Contact > contacts = [SELECT AccountId FROM Contact
WHERE AccountId IN: Trigger.OldMap.keyset()
];
if (contacts != null && contacts.size() > 0) {
delete contacts;
}
}
trigger undeleteContacts on Account(after undelete) {
List < Contact > contacts = [SELECT AccountId FROM Contact
WHERE AccountId IN: Trigger.OldMap.keyset()
AND IsDeleted = true ALL ROWS
];
if (contacts != null && contacts.size() > 0) {
undelete contacts;
}
}
6. Apex trigger to prevent Contact's expiry date on holiday.
trigger checkHoliday on Contact(before insert, before update) {
List < HoliDay > hList = new List < HoliDay > ([select id, Name, ActivityDate from HoliDay]);
for (Contact c: trigger.new) {
for (HoliDay h: hList) {
if (c.Expiry_Date__c == h.ActivityDate) {
c.addError('Expiry Date should not be on :' + h.Name);
}
}
}
}
7. Apex trigger to update Account Owner name in Account's Description.
Trigger updateOwnerName on Account(before insert, before update) {
Set < id > ownerIds = new Set < id > ();
for (Account a: Trigger.new)
ownerIds.add(a.OwnerId);
Map < id, User > owners = new Map < id, User > ([Select FirstName from User
Where Id in: ownerIds
]);
for (Account a: accList) {
a.Description = owners.get(a.OwnerId).FirstName;
}
}
8. Apex trigger to update child record when parent record is updated.
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;
}
}
9. 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();
}
10. Apex trigger to update Contact's Description with Account's Description.
trigger copyDescription on Contact(before insert, before update) {
set < id > AccountIds = new set < id > ();
Map < id, Account > mapAcc = new Map < id, Account > ();
for (Contact con: trigger.new) {
AccountIds.add(con.AccountId);
}
for (Account a: [select Id, Description from Account where ID in: AccountIds]) {
mapAcc.put(a.id, a);
}
for (Contact con: trigger.new) {
con.Description = mapAcc.get(con.AccountId).Description;
}
}
11. Trigger to update previous contact as non primary if new contact is primary.
Trigger updatePrimaryCheckbox2 on Contact(after insert, after update) {
Map < Id, Id > accConMap = new Map < Id, Id > ();
List < Contact > conList = new List < Contact > ();
for (Contact cont: Trigger.New) {
if (cont.AccountId != null && cont.IsPrimaryContact__c &&
(Trigger.isInsert || (Trigger.isUpdate &&
!Trigger.oldMap.get(cont.Id).IsPrimaryContact__c))) {
accConMap.put(cont.AccountId, cont.Id);
}
}
if(!accConMap.isEmpty())
{
for (Contact con: [select Id, IsPrimaryContact__c from contact
where accountid IN: accConMap.keyset() AND
Id NOT IN: accConMap.values()
AND IsPrimaryContact__c = true
])
{
con.IsPrimaryContact__c = false;
conList.add(con);
}
if(!conList.isEmpty()) {
update conList;
}
}
}
12. Restrict updating the existing email
trigger RestrictEmailUpdate on Contact(before update) {
for (Contact con: Trigger.new) {
if (con.Email != Trigger.oldMap.get(con.Id).Email) {
con.addError('Email cannot be changed..!');
}
}
}
13. Trigger to submit for approval
trigger accountApprovalSubmit on Account(after insert, after update) {
List < Approval.ProcessSubmitRequest > recordsToBeSubmitted =
new List < Approval.ProcessSubmitRequest > ();
for (Account acc: trigger.new) {
if (acc.Usage_Exclusion__c && (Trigger.isInsert ||
trigger.newMap.get(acc.id).Usage_Exclusion__c !=
trigger.oldMap.get(acc.id).Usage_Exclusion__c)) {
Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest();
request.setComments('Submitting request for approval.');
request.setObjectId(acc.Id);
recordsToBeSubmitted.add(request);
}
}
if (!recordsToBeSubmitted.isEmpty())
Approval.ProcessResult[] results = Approval.process(recordsToBeSubmitted, False);
//You can loop over the above results list and debug the result if you want.
}
14. trigger to send an email by comparring two values Postal code from Lead object and Zip code
from Zip_code__c custom object when both are equla then send an email to that particular zipcode assigned user.
trigger trgSendMailOnLead on Lead(before insert) {
Map < String, String > mapZipForEmail = new Map < String, String > ();
Postal code from Lead object and Zip code from Zip_code__c
for (Zip_code__c thisZipCode: [Select id, zipCode__c, assigned_user__c from Zip_code__c]) {
mapZipForEmail.put(thisZipCode.zipCode__c, thisZipCode.assigned_user__c)
}
// Create a master list to hold the emails
List < Messaging.SingleEmailMessage > mails = new List < Messaging.SingleEmailMessage > ();
for (Lead myLead: Trigger.new) {
if (mapZipForEmail.containsKey(myLead.PostalCode__c)) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// list of people who should get the email
List < String > sendTo = new List < String > ();
sendTo.add(mapZipForEmail.get(myLead.PostalCode__c));
mail.setToAddresses(sendTo);
// Set email is sent from
mail.setReplyTo('youremail@yourdomain.com');
mail.setSenderDisplayName('Your Name');
// Set email contents
mail.setSubject('URGENT BUSINESS PROPOSAL');
String body = 'Dear ' + myLead.FirstName + ', ';
body += 'Email Body.';
mail.setHtmlBody(body);
// Add your email to the master list
mails.add(mail);
}
}
// Send all emails in the master list
if (mails.size() > 0) Messaging.sendEmail(mails);
}
15. Create Opportunity Trigger with Helper class
trigger AccountTriggerWithHelperClass on Account(before insert, after insert,
before update, after update,
before delete, after delete,
after undelete) {
if (Trigger.isInsert && Trigger.isAfter) {
CreateOpportunityHelper.createOpportunity(Trigger.new);
}
}
public with sharing class CreateOpportunityHelper {
public static void createOpportunity(List < Account > accounts) {
List < Opportunity > listOpp = new List < Opportunity > ();
for (Account acc: accounts) {
Opportunity opp = new Opportunity();
opp.Name = acc.Name;
opp.CloseDate = System.Today();
opp.StageName = 'Qualification';
opp.AccountId = acc.Id;
opp.Description = 'Created from AccountTriggerWithHelperClass...!';
listOpp.add(opp);
}
insert listOpp;
}
}
16. Trigger to create Opportunity line item when Opportunity is created.
trigger Create_Opportunity_Line_Item_19 on Opportunity(after insert) {
Pricebook2 standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];
Product2 prd1 = new Product2(); // ----> Create product
prd1.Name = 'Accomodation';
prd1.isActive = true;
insert prd1;
System.debug(prd1);
PricebookEntry pbe1 = new PricebookEntry(); //------->Create PriceBookEntry
pbe1.Product2ID = prd1.id;
pbe1.Pricebook2ID = standardPb.id;
pbe1.UnitPrice = 50;
pbe1.isActive = true;
insert pbe1;
List < OpportunityLineItem > oplist =
new List < OpportunityLineItem > (); //-->Create List to store OpportunityLineItem
for (Opportunity opp: Trigger.New) {
OpportunityLineItem oppli =
new OpportunityLineItem(); //---->Create OpportunityLineItem.
oppli.PricebookEntryId = pbe1.Id;
oppli.OpportunityId = opp.Id;
oppli.Quantity = 5;
oppli.TotalPrice = 10.0;
oplist.add(oppli);
}
insert oplist; //----->insert OpportunityLineItem
}
17. Trigger to prevent the deletion Account record
if it has its related Opportunities:
trigger PreventAccountDeletion_3 on Account(before delete) {
for (Account acc: [SELECT ID From Account WHERE ID IN: Trigger.Old AND
ID IN(SELECT AccountId from Opportunity)]) {
trigger.oldMap.get(acc.Id).addError('Cannot delete Account with Opportunities');
}
}
public class CreateAdOpsTaskTriggerContext {
public static boolean executeTrigger = true;
}
18. Trigger to create task when stage = 'Ad6 - IO Received' and oldstage != newstage
trigger CreateAdOpsTask on Opportunity(after update) {
if (CreateAdOpsTaskTriggerContext.executeTrigger) {
CreateAddOpsTaskTriggerContext.executeTrigger = false;
List < Ad_Ops_Task__c > Ad_Ops_Tasks = new List < Ad_Ops_Task__c > ();
for (Opportunity oppty: Trigger.new) {
//Opportunity oldOppty = (Opportunity)Trigger.oldMap.get(oppty.id);
if (oppty.StageName == 'Ad6 - IO Received' &&
oppty.StageName != Trigger.oldMap.get(oppty.id).StageName) {
Ad_Ops_Task__c AOSTask = new Ad_Ops_Task__c();
AOSTask.Opportunity__c = oppty.Id;
AOSTask.Name = 'AdOps Task - ' + oppty.Name + ' - ' + oppty.Media_Plan_Id__c;
Ad_Ops_Tasks.add(AOSTask);
}
}
if (Ad_Ops_Tasks != null && Ad_Ops_Tasks.size() > 0) {
try {
Database.insert(Ad_Ops_Tasks, false);
} catch (Exception e) {
System.debug('Exception occurred. ' + e);
}
}
}
}
19. Trigger to create opportunity if Account doesn't have any opportunity
trigger AddRelatedRecord on Account(after insert, after update) {
List<Opportunity> oppList = new List<Opportunity>();
// Add an opportunity for each account if it doesn't already have one.
// Iterate over accounts that are in this trigger but that don't have opportunities.
for (Account a : [SELECT Id,Name FROM Account
WHERE Id IN :Trigger.New AND
Id NOT IN (SELECT AccountId FROM Opportunity)]) {
// Add a default opportunity for this account
oppList.add(new Opportunity(Name=a.Name + ' Opportunity',
StageName='Prospecting',
CloseDate=System.today().addMonths(1),
AccountId=a.Id));
}
if (oppList.size() > 0) {
insert oppList;
}
}
20. Trigger to update opportunity when Account is updated.
trigger DmlTriggerBulk on Account(after update) {
// Get the related opportunities for the accounts in this trigger.
List<Opportunity> relatedOpps = [SELECT Id,Name,Probability FROM Opportunity
WHERE AccountId IN :Trigger.New];
List<Opportunity> oppsToUpdate = new List<Opportunity>();
// Iterate over the related opportunities
for(Opportunity opp : relatedOpps) {
// Update the description when probability is greater
// than 50% but less than 100%
if ((opp.Probability >= 50) && (opp.Probability < 100)) {
opp.Description = 'New description for opportunity.';
oppsToUpdate.add(opp);
}
}
// Perform DML on a collection
update oppsToUpdate;
}
21. Trigger to update team member on Account
trigger UpdateTeamMember on Account (before update, before insert)
{
Set<Id> accountIds = new Set<Id>();
// get the Account Ids updated / inserted to be used in the following query
for (Account acctTeam : Trigger.new)
{
accountIds.add(acctTeam.Id);
}
//SOQL query moved outside of the Loop
// for each account updated get the related TeamMembers with a 'Manager' Role
List<Account> accounts = [Select Id, Industry_Manager__c,
(select User.Name from AccountTeamMembers where TeamMemberRole = 'Account Manager')
From Account Where Id IN :accountIds];
//Loop over the accounts if any were found
if(accounts != null && accounts.size() > 0 )
{
//Go through the accounts returned from the query
for(Account acc : accounts)
{
//If the manager has been removed, when the
//account is updated the field will return to null
if(acc.AccountTeamMembers == null || acc.AccountTeamMembers.size() == 0)
{
acc.Industry_Manager__c= null;
}
else if (acc.AccountTeamMembers.size() == 1)
{
acc.Industry_Manager__c= acc.AccountTeamMembers[0].User.Name;
}
else
{
//Many managers were attatched to this account
// Choose what to do here
// Error? / pick first from list?
}
upsert accounts;
}
}
}
******************** REST INTEGRATION ********************
------------------------------------------------------------
22. Rest web service to retrieve, create, delete, upsert, update records
@RestResource(urlMapping='/Cases/*')
global with sharing class CaseManager {
@HttpGet
global static Case getCaseById() {
RestRequest request = RestContext.request;
// grab the caseId from the end of the URL
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);
// Match case by Id, if present.
// Otherwise, create new case.
upsert thisCase;
// Return the case ID.
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;
}
}
23. 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>
******************** SOAP INTEGRATION ********************
------------------------------------------------------------
24. 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;
}
}
25. 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;
}
}
26. 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
******************** BATCH AND SCHEDULABLE APEX ********************
----------------------------------------------------------------------
27. Batch and schedulable apex to create child and grand child records.
global class batchContactCreate implements Database.Batchable<sObject>, Schedulable {
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator([
select Name, Date__c from Account where ID NOT IN (SELECT Account__c from S1_Customer__c)]);
}
global void execute(Database.BatchableContext BC, List<Account> scope) {
List<S1_Customer__c> cList = new List<S1_Customer__c>();
List<Task__c> invList = new List<Task__c>();
for(Account a : scope){
for(Integer i=0;i<2;i++){
S1_Customer__c cust = new S1_Customer__c();
cust.Name = a.Name;
cust.Account__c = a.Id;
cust.Phone__c = '1212121232';
cust.Date__c = a.Date__c.addDays(i));
cList.add(cust);
}
}
insert cList;
for(S1_Customer__c c:cList){
Task__c i = new Task__c();
i.Name= c.Name;
i.Customer__c = c.Id;
invList.add(i);
}
insert invList;
}
global void execute(SchedulableContext ctx){
batchContactCreate batch = new batchContactCreate();
Database.executebatch(batch, 200);
}
global void finish(Database.BatchableContext BC) {
}
}
******************** TEST CLASS ********************
----------------------------------------------------
28. Test class, Test Data utility class, ConstantsUtility class.
Test class:
@isTest(seeAllData=false)
private class AccountTriggerWithHelperClass_Test{
static testMethod void testHelperClass(){
List<Account> listAccs = TestDataUtility.createAccounts();
insert listAccs;
}
}
Test Data utility class:
public class TestDataUtility{
public static List<Account> createAccounts(){
List<Account> accts = new List<Account>();
for(Integer i=0;i<20;i++) {
Account a = new Account(Name= ConstantsUtility.ACCOUNTNAME + i);
accts.add(a);
}
return accts;
}
}
Constants Utility class:
public class ConstantsUtility {
public static String ACCOUNTNAME = 'Test Account';
public static String ACCOUNTOBJ = 'Account';
public static String CONTACTOBJ = 'Contact';
}
******************* LIGHTNING ******************
------------------------------------------------
29. Lightning component to create a record.
Apex controller:
public class LC_1_InsertLeadRecordsCtr {
@AuraEnabled
public static void createLead(Lead le){
insert le;
}
}
Component:
<aura:component controller="LC_1_InsertLeadRecordsCtr" implements="force:appHostable" >
<aura:attribute name='lea' type='Lead' default="{sobjecttype:'Lead'}"/>
<lightning:input label='LastName' value='{!v.lea.LastName}'/>
<lightning:input label='Company' value='{!v.lea.Company}'/>
<lightning:input label='Status' value='{!v.lea.Status}'/>
<lightning:button label='submit' onclick='{!c.submitfunction}'/>
</aura:component>
controller:
({
submitfunction : function(component, event, helper) {
var lee = component.get('v.lea');
var a = component.get('c.createLead');
a.setParams({'le':lee});
a.setCallback(this,function(r){
component.set('v.lea',r.getReturnValue());
});
$A.enqueueAction(a);
},
})
lightning app:
<aura:application extends="force:slds">
<c:LC_1_InsertLeadRecords/>
</aura:application>
30. Lightning component to display data table with edit and view buttons.
Controller:
// Source: http://www.infallibletechie.com/2018/02/forceeditrecord-example-in-salesforce.html
public class LC_4_DataTableWithEditButton {
@AuraEnabled
public static List < Account > fetchAccts() {
return [ SELECT Id, Name, Industry FROM Account LIMIT 10 ];
}
}
Coomponent:
<aura:component controller="LC_4_DataTableWithEditButton"
implements="flexipage:availableForAllPageTypes,lightning:actionOverride,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:appHostable" >
<aura:attribute type="Account[]" name="acctList"/>
<aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
<aura:handler event="force:navigateToSObject" action="{!c.navigateToRecord}"/>
<lightning:card>
<table class="slds-table slds-table_bordered slds-table_cell-buffer">
<thead>
<tr class="slds-text-title_caps">
<th scope="col">
<div class="slds-truncate" title="Account Name">Account Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Account Name">Industry</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Action">Actions</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.acctList}" var="a">
<tr>
<td data-label="Account Name">
<div class="slds-truncate" title="">{!a.Name}</div>
</td>
<td data-label="Industry">
<div class="slds-truncate" title="">{!a.Industry}</div>
</td>
<td>
<button class="slds-button slds-button_brand" onclick="{!c.editAccount}" id="{!a.Id}">Edit</button>
</td>
<td>
<button class="slds-button slds-button_brand" onclick="{!c.viewAccount}" id="{!a.Id}">View</button>
</td>
<td>
<lightning:button variant="success" label="Navigate To URL" title="Navigate To Salesforce.com" onclick="{! c.navigateToURL }"/>
</td>
</tr>
</aura:iteration>
</tbody>
</table>
</lightning:card>
</aura:component>
Controller:
({
fetchAccounts : function(component, event, helper) {
var action = component.get("c.fetchAccts");
action.setParams({
});
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.acctList", response.getReturnValue());
}
});
$A.enqueueAction(action);
},
editAccount : function(component, event, helper) {
var editRecordEvent = $A.get("e.force:editRecord");
editRecordEvent.setParams({
"recordId": event.target.id
});
editRecordEvent.fire();
},
viewAccount : function(component, event, helper) {
var editRecordEvent = $A.get("e.force:navigateToSObject");
editRecordEvent.setParams({
"recordId": event.target.id
});
//window.open('/' + event.getParam('recordId'));
editRecordEvent.fire();
},
navigateToURL : function(component, event, helper) {
var urlEvent = $A.get("e.force:navigateToURL");
urlEvent.setParams({
"url": 'https://www.salesforce.com/' ,
"isredirect":true ,
});
urlEvent.fire();
}
})
Lightning app:
<aura:application extends="force:slds">
<c:LC_4_DataTableWithEditButton />
</aura:application>
*************** LIGHTNING WEB COMPONENT *****************
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>
{acc.Site}
</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));
});
}
}
<aura:application extends="force:slds">
<c:updateAccount/>
</aura:application>
*/
}
No comments:
Post a Comment