1. Before Insert Trigger: Apex trigger to update account description with Account Name and Account Number.
trigger BeforeInsertTrigger on Account (before insert)
{
for(Account acc: Trigger.new){
if(String.isBlank(acc.Description)){
acc.Description = acc.Name + ' '+acc.AccountNumber;
}
}
}
==================================
2. Apex trigger to update Account Rating when Account is created or updated .
Trigger Name: BeforeInsertUpdateTrigger2
Description: Apex trigger to update Account Rating when Account is created or
updated as per below requirement.
update Account Rating as Hot if
Account Industry is Banking
update Account Rating as Warm if Industry is Biotechnology
else update Account Rating as Cold
trigger BeforeInsertUpdateTrigger2 on Account (before insert, before update) {
for(Account acc: Trigger.new){
if(String.isNotBlank(acc.Industry)){
if(acc.Industry == 'Banking'){
acc.Rating = 'Hot';
}
else if(acc.Industry == 'Biotechnology'){
acc.Rating = 'Warm';
}
else
{
acc.Rating = 'Cold';
}
}
}
}
=========================================
3. Apex Trigger to restrict the creation duplicate account with same account name.
trigger BefoerInsertTrigger4 on ContentDocument (before insert) {
4. Before Insert & Before Update Trigger:
Trigger to prevent duplicate primary contacts for the same account.
An account should not have more than one primary conatct.
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');
}
}
}
}
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 triiger to restrict the deletion of Contact record if it is Primary contact.
trigger BefoerDeleteTrigger on Contact (before delete) {
for(Contact con: Trigger.old){
if(con.Primary__c){
con.Primary__c.addError('Primary contact cannot be deleted.');
}
}
}
9. 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');
}
}
}
}
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;
}
}
}
=======================
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 ! ');
}
}
}
}
====================
12. 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();
}
}
==========================
13. 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;
}
}
}
===================================
14. 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);
}
}
}
===================================
15. 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();
}
/*
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');
} */
}
===========================
18, 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);
}
}
}
===========================
19. 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;
}
*/
}
==========================================
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;
}
}
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;
}
}
26. Apex trigger to send pdf along with email when contact is created.
trigger sendEmail on Employee__c (after insert, after update) {
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for(Employee__c e : trigger.new) {
Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.setContentType(‘application/pdf’);
attach.setFileName(‘Employee.pdf’);
String body;
body = ‘<html><h1 style=”text-align:center;”>Employee Information</h1><br/><br/><table align=”center”><tr><td>Employee Name</td><td>’ + e.Name + ‘</td></tr><tr><td>Age</td><td>’ + e.Age__c + ‘</td></tr><tr><td>State</td><td>’ + e.State__c + ‘</td></tr><tr><td>City</td><td>’ + e.City__c + ‘</td></tr></table></html>’;
System.debug(‘HTML is ‘ + body);
attach.Body = Blob.toPDF(body);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] { e.Email__c });
mail.setSubject(‘PDF Generation’);
mail.setHtmlBody(‘PFA’);
mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });
mails.add(mail);
}
if(!mails.isEmpty()) {
Messaging.SendEmail(mails);
}
}
========================
27. Trigger to create chatter post:
trigger FieldHistory on Member__c (after insert, after update) {
Map<Id, Member__c> MemberMap = trigger.oldMap;
List<FeedItem> FIList = new List<FeedItem>();
if(trigger.isInsert) {
for(Member__c Mem : trigger.new) {
FeedItem FI = new FeedItem();
FI.Body = ‘Member Created’;
FI.ParentId = Mem.Id;
FIList.add(FI);
}
insert FIList;
}
if(trigger.isUpdate) {
for(Member__c Mem : trigger.new) {
Member__c OldMem = new Member__c();
OldMem = MemberMap.get(Mem.Id);
if(Mem.Area__c != OldMem.Area__c) {
FeedItem FI = new FeedItem();
FI.Body = ‘Area changed from ‘ + OldMem.Area__c + ‘ to ‘ + Mem.Area__c;
FI.ParentId = Mem.Id;
FIList.add(FI);
}
}
if(!FIList.isEmpty()){
insert FIList;
}
}
}
====================
28. Trigger to create Opportunity line item when Opportunity is created.
29. Trigger to fetch values from Custom Metadata type and update in ISO__c field of Account:
No comments:
Post a Comment