Sunday, 23 October 2022

Apex Triggers Scenarios

//1. Before Insert Trigger: Apex trigger to update account description with Account Name and  Account Number.


trigger BeforeInsertTrigger1 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;

                }

            }

        }

    }

*/

}

=================

trigger BeforeInsertTrigger2 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';


                }


            }


        }


    }


*/

}

===========================

trigger BeforeInsertTrigger3 on Account (before insert, before update) {

   /*

    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 ! ');

            

        }

        

    }*/

    

}

==========================

trigger BeforeInsertTrigger4 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, 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: Trigger.New) {

   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');

    }

   }

  } */

 }

========================

trigger AfterInsertTrigger5 on Account (after insert) {

    

    List<Contact> listCon = new List<Contact>();

    

    for(Account acc: Trigger.new){

        

        Contact con = new Contact();

        

        con.LastName = acc.Name + ' Contact';

        con.Description = acc.Description;

        

        con.AccountId = acc.Id;

        

        listCon.add(con);

        

    }

    

    if(!listCon.isEmpty()){

        

        try {

            

            Database.insert(listCon, false);

            

        }

        

        catch(Exception ex){

            

            System.debug('Exception occurred '+ex);

            

        }

        

    } 

    

    

}

====================

trigger BeforeUpdateTrigger6 on Account (before update) {

/*

      for(Account acc: Trigger.new){

          

          if(Trigger.oldMap.get(acc.Id).AccountNumber != null){

               if(acc.AccountNumber != Trigger.oldMap.get(acc.Id).AccountNumber){


                    acc.addError('Cannot change the Account Number');


                }

          }

         

      }*/

}

====================

trigger AfterUpdateTrigger7 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 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;

        

    } */

    

}

===============================

trigger AfterUpdateTrigger8 on Contact (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();

    */

  }

=====================

trigger BeforeDeleteTrigger9 on Account (before delete) {

    /*

    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 BeforeDeleteTrigger10 on Contact (before delete) {

    /*

    for(Contact con: Trigger.old){

        

        if(con.Primary__c){

            

            con.Primary__c.addError('Primary contact cannot be deleted.');

            

        }

        

    } */

}

=======================

trigger AfterDeleteTrigger11 on Contact (after delete) {

/*

     List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();


            for (Contact con : Trigger.old) {


                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 deleted');


                    String body = 'Dear ' + con.LastName + ', '; 


                    body += 'Your Contact is deleted successfully in Salesforce org.';


                    mail.setHtmlBody(body);


                    mails.add(mail);


                }


            }


            Messaging.sendEmail(mails);

*/

}

=========================

trigger AfterUnDeleteTrigger12 on Account (after undelete) {

    /*

     List<Account> listAccount = new List<Account>();


            for(Account acc : [SELECT ID, Name, Description from Account where Id IN : trigger.new]){ 


                acc.Name = 'Restored Account: ' + acc.Name;


                acc.Description = 'This Account is restored by Trigger';


                listAccount.add(acc);


            } 


            update listAccount;

*/

        }

===============================

trigger AfterInsertUpdateTrigger13 on Contact (after insert) {

/*

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;

        }

    }

*/

}

=======================

trigger AfterInsertTrigger14 on Opportunity (after insert) {

    /*

    List<Task> listTask = new List<Task>();

    

    for(Opportunity opp: Trigger.new)

        

    {

        if(opp.StageName == 'Closed Won' ){

            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);

            

        }

        

    }

    */

}

==============================

trigger AfterInsertUpdateTrigger15 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();

    }

*/

}

============================

Trigger AfterInsertUpdateTrigger16 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;

*/

 }

=======================

trigger ContentDocumentTrigger17 on ContentDocument (before insert) {


    for(ContentDocument cd : trigger.new) {


        if(cd.Title == 'Test1') {

            cd.addError('Name should not be Test');

            cd.Title.addError('Name should not be Test');


        }

    }

}

===================

18. 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);

        }

    }

}


19. 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');

        }

    }

    */

}

==================
20. Trigger to create contacts based on given number whenever Account is created.


Trigger:

trigger AccountTrigger1 on Account (after insert) {
    
   AccountTrigger1Handler.createContacts(Trigger.new);
}

Trigger Handler:

public class AccountTrigger1Handler {
    public static void createContacts(List<Account> listAccount){
        List<Contact> listContact = new List<Contact>();
        for(Account acc: listAccount){
            for(Integer i=0; i < acc.Number_of_Contacts__c; i++ ){
                Contact con = new Contact();
                con.AccountId = acc.Id;
                con.LastName = acc.Name + 'Contact '+i;
                listContact.add(con);
            }
        }
        
        if(listContact.size() > 0 && !listContact.isEmpty()){
            try{
                Database.insert(listContact, false);
            }
            catch(Exception e){
                System.debug('Error occurred '+e);
            }
        }
    }
}

========================

21. 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);
   }
  }
 }

========================

22. Cant delete attachment for completed Case

trigger ContentDocumentLinkTriggerDelete on ContentDocumentLink (before delete) {
    System.debug('ContentDocumentLinkTriggerDelete');
    if(trigger.isBefore) {
        if(trigger.isDelete) {
            System.debug('inside before delete @@@ ');
            Map<Id, Case> closedCasesMap = new Map<Id, Case>();
            for(Case cs: [Select Id from Case  where Status = 'Completed'  ]){
                closedCasesMap.put(cs.Id, cs);
                System.debug('closedCasesMap ==> ' +closedCasesMap);
            }
            for(ContentDocumentLink a : Trigger.old) {
                System.debug('ContentDocumentLink parent id: ' +a.Id);
                if(closedCasesMap.containsKey(a.LinkedEntityId)){
                    a.addError('Cant delete attachment for completed Case');
                }
            } 
        }
    }  /*
    for(ContentDocumentLink a : Trigger.old) {
        a.addError('cant delete @@@');
    }
    */
}

23. 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.
  }

24. 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;
  }
 }

============================
25. Send email with pdf after 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);
    }
}

============================
26. 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;
    }
}

No comments:

Post a Comment