Apex Triggers Examples - updated

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

   
        Set<String> fileNameSet = new Set<String>();

        for(ContentDocument acc: [SELECT Title FROM ContentDocument]){

            fileNameSet.add(acc.Title);

            System.debug('fileNameSet @@ '+fileNameSet);

        }

        for(ContentDocument acc: trigger.new){

            if(fileNameSet.contains(acc.Title)){

                System.debug('fileNameSet.contains(acc.Name) '+acc.Title);

                acc.title.addError('A file exists with same ttlr ! ');
                acc.addError('A file exists with same ttlr ]]]! ');

            }

        }

    }

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

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

===============================
5. 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);

                }

            } 

        }

    }

}


5. Trigger with Helper Class
Trigger:

Trigger AccountTrigger on Account(Before Insert, Before Update, Before Delete, 
 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');

        }

    }

    */

}

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

16. Apex trigger to update Account record when Contact 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();
  }

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

17. Apex Trigger to create Account for contact if account is not associated with contact.

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

    } */


}

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

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;

    }

*/

}

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


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 on ContentDocument:

trigger BefoerInsertTrigger4 on ContentDocument (before insert) {
   
        Set<String> fileNameSet = new Set<String>();

        for(ContentDocument acc: [SELECT Title FROM ContentDocument]){

            fileNameSet.add(acc.Title);

            System.debug('fileNameSet @@ '+fileNameSet);

        }

        for(ContentDocument acc: trigger.new){

            if(fileNameSet.contains(acc.Title)){

                System.debug('fileNameSet.contains(acc.Name) '+acc.Title);

                acc.title.addError('A file exists with same ttlr ! ');
                acc.addError('A file exists with same ttlr ]]]! ');

            }

        }

    }

==========================
22. Trigger on ContentDocumentLink

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.  Trigger on Note object.

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.


  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
  }

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

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


30. Restrict the deletion of Account record for a user with System Administrator profile.

trigger RestrictDeletion1 on Account (before delete) {
    
    //Id profileId = UserInfo.getProfileId();
    String profileName = [SELECT Id, Name FROM Profile WHERE Id=: UserInfo.getProfileId()].Name;
    for(Account acc: Trigger.old){
        if(profileName == 'System Administrator'){
            acc.addError('User with System Admin profile cannot delete Account ');
        }
    }
}

31. Restrict the deletion of Account record with user name Sohel.

trigger RestrictDeletion2 on Account (before delete) {
    String username = UserInfo.getName();
    for(Account acc: trigger.old){
        if(username.contains('Sohel')){
            acc.addError('User with name Sohel cannot delete Account ');
        }
    }
}

32. Restrict the deletion of Account record if User with Delete__c =true.

trigger RestrictDeletion3 on Account (before delete) {
    Id userId = UserInfo.getUserId();
    Boolean userDelete = [SELECT Id, Delete__c FROM User WHERE Id=: userId].Delete__c;
    for(Account acc: trigger.old){
        if(userDelete){
            acc.addError('User with Delete__c =true  cannot delete Account ');
        }
    }
}

No comments:

Post a Comment