1. Before Insert Trigger: Apex trigger to update account description with Account Name and Account Number.
trigger BeforeInsertTrigger on Account (before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
if(Trigger.isInsert){
if(Trigger.isBefore){
for(Account acc: Trigger.new){
if(String.isBlank(acc.Description)){
acc.Description = acc.Name + ' '+acc.AccountNumber;
}
}
}
}
}
2.
trigger BeforeInsertTrigger on Account (before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
if(Trigger.isInsert || Trigger.isUpdate){
if(Trigger.isBefore){
for(Account acc: Trigger.new){
if(String.isNotBlank(acc.Industry)){
if(acc.Industry == 'Banking'){
acc.Rating = 'Hot';
}
else if(acc.Industry == 'Agriculture'){
acc.Rating = 'Warm';
}
else
acc.Rating = 'Cold';
}
}
}
}
}
2. Before Insert & Before Update Trigger: Trigger to prevent duplicate primary contacts:
Trigger PrimaryContactChecking on Contact(before insert, before 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');
}
}
}
}
4. After Insert Trigger: Apex trigger to create Contact when Account is created.
trigger AfterInsertTrigger on Account (before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
if(Trigger.isInsert){
if(Trigger.isAfter){
List<Contact> listCon = new List<Contact>();
for(Account acc: Trigger.new){
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 occurred '+ex);
}
}
}
}
}
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. Before Update Trigger: Apex Trigger to restrict the change of Account Number of Account record.
trigger BeforeUpdateTrigger on Account (before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
if(Trigger.isUpdate){
if(Trigger.isBefore){
for(Account acc: Trigger.new){
if(acc.AccountNumber != Trigger.oldMap.get(acc.Id).AccountNumber){
acc.addError('Cannot change the Account Number');
}
}
}
}
}
7. Apex Trigger to update Contact Description whenever Account Description is updated.
trigger AfterUpdateTrigger on Account (before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
if(Trigger.isUpdate){
if(Trigger.isAfter){
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 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;
}
}
}
}
8. Apex Trigger to restrict to delete the Account if it has related Contacts.
trigger BeforeDeleteTrigger on Account (before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
if(Trigger.isDelete){
if(Trigger.isBefore){
for (Account acc: [SELECT ID From Account WHERE ID IN: Trigger.old AND
ID IN(SELECT AccountId from Contact)])
{
trigger.oldMap.get(acc.Id).addError('Cannot delete Account with contacts');
}
}
}
}
9. trigger BefoerDeleteTrigger on Contact (before delete) {
for(Contact con: Trigger.old){
if(con.Primary__c){
con.Primary__c.addError('Primary contact cannot be deleted.');
}
}
}
trigger BefoerDeleteTrigger on Contact (before delete) {
for(Contact con: Trigger.old){
if(con.Primary__c){
con.Primary__c.addError('Primary contact cannot be deleted.');
}
if(UserInfo.getUserId() != con.ownerid){
con.addError('only record owner can delete');
}
}
}
10. Apex Trigger to send Email to Contact Email address when Contact is deleted.
trigger AfterDeleteTrigger on Contact (before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
if(Trigger.isDelete){
if(Trigger.isAfter){
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for (Contact acc : Trigger.old) {
if (acc.Email__c != null) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> sendTo = new List<String>();
sendTo.add(acc.Email);
mail.setToAddresses(sendTo);
mail.setSubject('Your Account is deleted');
String body = 'Dear ' + acc.Name + ', ';
body += 'Your Contact is deleted successfully in Salesforce org.';
mail.setHtmlBody(body);
mails.add(mail);
}
}
Messaging.sendEmail(mails);
}
}
}
11. Apex trigger to update Account Name when Account is undeleted.
trigger AfterUndeleteTrigger on Account (before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
if(Trigger.isUndelete){
if(Trigger.isAfter){
List<Account> listAccount = new List<Account>();
for(Account acc : [SELECT ID, Name, Description from Account where Id IN : trigger.new]){
acc.Name = 'Undeleted Account: ' + acc.Name;
acc.Description = 'This Account is undeleted by Trigger';
listAccount.add(acc);
}
update listAccount;
}
}
}
12. Apex trigger to restrict the creation of duplicate account.
public static void beforeInsert2(List<Account> newAccounts){
Set<String> accountNameSet = new Set<String>();
for(Account acc: [SELECT Name FROM Account]){
accountNameSet.add(acc.Name);
System.debug('accountNameSet @@ '+accountNameSet);
}
for(Account acc: newAccounts){
if(accountNameSet.contains(acc.Name)){
System.debug('accountNameSet.contains(acc.Name) '+acc.Name);
acc.Name.addError('An Account exists with same name ! ');
}
}
}
}
13. Trigger to count, sum, min, max, avg of child records using Aggregate Result:
Trigger ContactAggregateResult on Contact(after insert){
Set<Id> accountIdSet = new Set<Id>();
Map<Id, Account> accountMap = new Map<Id, Account>();
for(Contact con: Trigger.new){
if(con.AccountId != null){
accountIdSet.add(con.AccountId);
}
}
if(accountIdSet != null){
for(AggregateResult ar: [SELECT count(Id) contactCount, sum(Amount__c) sumAmount,
avg(Amount__c) avgAmount, Max(Amount__c) maxAmount,
min(Amount__c) minAmount, AccountId FROM Contact
WHERE AccountId in: accountIdSet GROUP BY AccountId ])
{
Account acc = new Account();
acc.Id = (Id)ar.get('AccountId');
acc.Count_of_Contacts__c = (Integer)ar.get('contactCount');
acc.Sum_of_Contacts_Amount__c = (Decimal)ar.get('sumAmount');
acc.Max_of_Contacts_Amount__c = (Decimal)ar.get('maxAmount');
acc.Min_of_Contacts_Amount__c = (Decimal)ar.get('minAmount');
acc.Average_Of_Contacts_Amount__c = (Decimal)ar.get('avgAmount');
accountMap.put(acc.Id, acc);
}
}
if(accountMap != null){
update accountMap.values();
}
}
14. Update previous contact as non primary.
trigger Trigger9_UpdatePreviousContactAsNonPrimary 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.Primary__c &&
(Trigger.isInsert || (Trigger.isUpdate &&
!Trigger.oldMap.get(cont.Id).Primary__c))) {
accConMap.put(cont.AccountId, cont.Id);
}
}
if(!accConMap.isEmpty())
{
for (Contact con: [select Id, Primary__c from contact
where accountid IN: accConMap.keyset() AND
Id NOT IN: accConMap.values()
AND Primary__c = true
])
{
con.Primary__c = false;
conList.add(con);
}
if(!conList.isEmpty()) {
update conList;
}
}
}
15. Create Task For Closed Opp
trigger Trigger10_CreateTaskForClosedOpp on Opportunity (after insert) {
List<Task> listTask = new List<Task>();
for(Opportunity opp: [SELECT Id, StageName FROM Opportunity
WHERE StageName = 'Closed Won' AND ID IN: Trigger.new])
{
Task t = new Task();
t.Subject = 'Follow up task';
t.WhatId = opp.Id;
listTask.add(t);
}
if(!listTask.isEmpty()){
try{
Database.insert(listTask, false);
}
catch(Exception ex){
System.debug('Exception '+ex);
}
}
}
16. Duplicate Lead ContactEmail
trigger Trigger13_DuplicateLeadContactEmail on Lead (before insert) {
/*
Set<String> leadEmailSet = new Set<String>();
for(Lead l: Trigger.new){
leadEmailSet.add(l.Email);
}
Map<String, Lead> leadMap = new Map<String, Lead>();
for(Lead l: [SELECT Id, Email FROM Lead WHERE Email in: leadEmailSet ]){
leadMap.put(l.Email, l);
}
for(Lead l: Trigger.new){
if(leadMap.containsKey(l.Email)){
l.addError(' Lead is already existed with this Email');
}
}
Map<String, Contact> conMap = new Map<String, Contact>();
for(Contact con: [SELECT Id, Email FROM Contact WHERE Email in: leadEmailSet]){
conMap.put(con.Email, con);
}
for(Lead l: Trigger.new){
if(conMap.containsKey(l.Email)){
l.addError('Contact is already existed with this Email');
}
}
*/
}
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();
}
trigger Trigger4_CreateAccountForContact on Contact (before insert, after insert) {
/*
if(trigger.isBefore){
system.debug('trigger before event');
if(trigger.isInsert){
List<Contact> listOfContact = new List<Contact>();
for (Contact conObj : trigger.new)
{
if (String.isBlank(conObj.accountid))
{
listOfContact.add(conObj);
}
}
system.debug('listOfContact_1 ' + listOfContact);
if (listOfContact.size() > 0)
{
List<Account> createNewAcc = new List<Account>();
Map<String,Contact> conNameKeys = new Map<String,Contact>();
for (Contact con : listOfContact)
{
String accountName = con.firstname + ' ' + con.lastname;
conNameKeys.put(accountName,con);
Account accObj = new Account();
accObj.Name = accountName;
accObj.Phone= con.MobilePhone;
createNewAcc.add(accObj);
}
Insert createNewAcc;
for (Account acc : createNewAcc)
{
system.debug('mapContainsKey ' + conNameKeys.containsKey(acc.Name));
if (conNameKeys.containsKey(acc.Name))
{
conNameKeys.get(acc.Name).accountId = acc.Id;
}
}
}
}
}
else if(trigger.isAfter){
system.debug('trigger after event');
} */
}
19, Delete Child WhenParent is Deleted
trigger DeleteChildWhenParentDeleted on ParentObject__c (before delete) {
Set<Id> parentIds = new Set<Id>();
for(ParentObject__c p: Trigger.old){
parentIds.add(p.Id);
}
List<ChildObject__c> c =[SELECT Id FROM ChildObject__c WHERE ParentObject__c IN: parentIds];
if(!c.isEmpty()){
try{
delete c;
}
catch(Exception ex){
System.debug('Exception '+ex);
}
}
}
20. Store new and old values using trigger.
trigger Trigger14_StoreNewOldValues on Account (before update) {
/*
for(Account acc: Trigger.new){
acc.Description = 'Account New Name: ' +acc.Name + 'Account old Name: ' +Trigger.oldMap.get(acc.Id).Name;
}
*/
}
21. Trigger to fetch values from Custom Metadata type and update in ISO__c field of Account:
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.
}
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;
}
}
Basically you need to create the ContentDocumentLink to link it to both the ContentNote and the sObject.
trigger AddNote on Lead (after insert) { List<ContentNote> nte = new List<ContentNote>(); List<ContentDocumentLink> lnk = new List<ContentDocumentLink>(); for(Lead lds : Trigger.new){ ContentNote cnt = new ContentNote(); cnt.Content = Blob.valueof(lds.Sales_Notes__c); cnt.Title = 'Creation Note'; nte.add(cnt); } if(nte.size()>0){ insert nte; } for(Lead lds : Trigger.new){ ContentDocumentLink clnk = new ContentDocumentLink(); clnk.LinkedEntityId = lds.Id; clnk.ContentDocumentId = nte[0].Id; clnk.ShareType = 'I'; lnk.add(clnk); } if(nte.size()>0){ insert lnk; } }
====================
trigger AccountTrigger on Account (before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
if(Trigger.isInsert){
if(Trigger.isBefore){
AccountTriggerHandler.beforeInsert(Trigger.new);
}
else if(Trigger.isAfter){
AccountTriggerHandler.beforeInsert(Trigger.new);
}
}
else if(Trigger.isUpdate){
if(Trigger.isBefore){
AccountTriggerHandler.beforeUpdate(Trigger.new, Trigger.newMap);
}
else if(Trigger.isAfter){
AccountTriggerHandler.afterUpdate(Trigger.new);
}
}
else if(Trigger.isDelete){
if(Trigger.isBefore){
AccountTriggerHandler.beforeDelete(Trigger.old);
}
else if(Trigger.isAfter){
AccountTriggerHandler.afterDelete(Trigger.old);
}
}
else if(Trigger.isUndelete){
if(Trigger.isAfter){
AccountTriggerHandler.afterUndelete(Trigger.new);
}
}
}
============================================
//Trigger handler of trigger 'AccountTrigger'
public class AccountTriggerHandler {
// 1.Before Insert - update account description
public static void beforeInsert(List<Account> newAccouts){
for(Account acc: newAccouts){
if(String.isBlank(acc.Description)){
acc.Description = acc.Name + ' '+acc.Description;
}
}
}
// 2.After Insert - create Contact whenever Account is created.
public static void afterInsert(List<Account> newAccouts){
List<Contact> listCon = new List<Contact>();
for(Account acc: newAccouts){
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 occurred '+ex);
}
}
}
// 3. before update - Restrict to change Account Number of Account record.
public static void beforeUpdate(List<Account> newListAcc, Map<Id, Account> oldAccountMap){
for(Account acc: newListAcc){
if(oldAccountMap.get(acc.Id).AccountNumber != acc.AccountNumber){
Trigger.oldMap.get(acc.Id).addError('Cannot change AccountNumber');
}
}
}
// 4. After Update - Update Contact whenever Account is updated.
public static void afterUpdate(List<Account> newAccouts){
Map < Id, Account > mapAccount = new Map < Id, Account > ();
List < Contact > listContact = new List < Contact > ();
for (Account acct: newAccouts)
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;
}
}
// 5. before delete - Restrict to delete the Account if it has related Contacts.
public static void beforeDelete(List<Account> oldListAcc){
for (Account acc: [SELECT ID From Account WHERE ID IN: oldListAcc AND
ID IN(SELECT AccountId from Contact)])
{
trigger.oldMap.get(acc.Id).addError('Cannot delete Account with contacts');
}
}
// 6. After Delete - Send Email to Account when Account is deleted.
public static void AfterDelete(List<Account> oldListAcc){
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for (Account acc : oldListAcc) {
if (acc.Email__c != null) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> sendTo = new List<String>();
sendTo.add(acc.Email__c);
mail.setToAddresses(sendTo);
mail.setSubject('Your Account is deleted');
String body = 'Dear ' + acc.Name + ', ';
body += 'Your Account is deleted successfully in Salesforce org.';
mail.setHtmlBody(body);
mails.add(mail);
}
}
Messaging.sendEmail(mails);
}
// 7. After Undelete -
public static void AfterUndelete(List<Account> newListAcc){
List<Account> listAccount = new List<Account>();
for(Account acc : [SELECT ID, Name, Description from Account where Id IN : newListAcc]){
acc.Name = 'Undeleted Account: ' + acc.Name;
acc.Description = 'This Account is undeleted by Trigger';
listAccount.add(acc);
}
update listAccount;
}
// 8. Before Insert - Restrict creation of duplicate account by account name.
public static void beforeInsert2(List<Account> newAccounts){
Set<String> accountNameSet = new Set<String>();
for(Account acc: [SELECT Name FROM Account]){
accountNameSet.add(acc.Name);
System.debug('accountNameSet @@ '+accountNameSet);
}
for(Account acc: newAccounts){
if(accountNameSet.contains(acc.Name)){
System.debug('accountNameSet.contains(acc.Name) '+acc.Name);
acc.Name.addError('An Account exists with same name ! ');
}
}
}
}
=======================================================
//Trigger handler of trigger 'AccountTrigger'
public class ContactTriggerHandler {
// 1.Before Insert - Restrict the creation of duplicate primary contact
public static void beforeInsert(List<Contact> newAccouts){
Set < Id > accountIdSet = new Set < id > ();
Map < Id, List < Contact >> accountIdContactMap =
new Map < Id, List < Contact >> ();
Account acc = new Account();
for (Contact con: newAccouts) {
accountIdSet.add(con.AccountId);
}
for (Contact con: [SELECT Id, Primary__c, AccountId FROM Contact
WHERE AccountId =: accountIdSet AND Primary__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: newAccouts) {
if ((accountIdContactMap.containsKey(con.AccountId)) &&
(con.AccountId != NULL) && (con.Primary__c == TRUE)) {
{
con.Primary__c.addError('Primary Contact already exists');
con.addError('Primary Contact already exists');
}
}
}
}
// 2.After Insert -
public static void afterInsert(List<Contact> newContacts){
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for (Contact con : newContacts) {
if (con.Email != null) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> sendTo = new List<String>();
sendTo.add(con.Email);
mail.setToAddresses(sendTo);
mail.setSubject('Your Contact is created');
String body = 'Dear ' + con.LastName + ', ';
body += 'Your Contact is created successfully in Salesforce org.';
mail.setHtmlBody(body);
mails.add(mail);
}
}
Messaging.sendEmail(mails);
}
// 3. before update -
public static void beforeUpdate(List<Contact> newListAcc, Map<Id, Contact> oldAccountMap){
}
// 4. After Update -
public static void afterUpdate(List<Contact> newAccouts){
}
// 5. before delete -
public static void beforeDelete(List<Contact> oldListAcc){
}
// 6. After Delete -
public static void AfterDelete(List<Contact> oldListAcc){
}
// 7. After Undelete -
public static void AfterUndelete(List<Contact> oldListAcc){
}
}
======================
trigger ContactTrigger on Contact(before insert, before update, before delete,
after insert, after update, after delete, after undelete)
{
if(Trigger.isInsert){
if(Trigger.isBefore){
ContactTriggerHandler.beforeInsert(Trigger.new);
}
else if(Trigger.isAfter){
ContactTriggerHandler.afterInsert(Trigger.new);
}
}
else if(Trigger.isUpdate){
if(Trigger.isBefore){
ContactTriggerHandler.beforeUpdate(Trigger.new, Trigger.newMap);
ContactTriggerHandler.beforeInsert(Trigger.new);
}
else if(Trigger.isAfter){
ContactTriggerHandler.afterUpdate(Trigger.new);
}
}
else if(Trigger.isDelete){
if(Trigger.isBefore){
ContactTriggerHandler.beforeDelete(Trigger.old);
}
else if(Trigger.isAfter){
ContactTriggerHandler.afterDelete(Trigger.old);
}
}
else if(Trigger.isUndelete){
if(Trigger.isAfter){
ContactTriggerHandler.afterUndelete(Trigger.new);
}
}
}
No comments:
Post a Comment