Triggers

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

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

Trigger to prevent duplicate Accounts:
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) + '.');
   }
  }
 }

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
  }

Populate sum of child field values on parent using apex trigger


Let’s say account is your parent object and Contact is your child object.
You have a field Salary on Contact and you have Total Salary field on Account.
Now your requirement is to add all child record’s salary and update the Total salary field on Parent Record.
The below code will be useful to overcome this need.

 
Set<id> accIds = new Set<id>();
        List<Account> lstAccToUpdate = new List<Account>();
        for(Contact c: lstCon){
            if(c.AccountId!=null){
                accIds.add(c.AccountId);
            }
        }
        for(Account a : [select id,name,Total_Salary__c,(select id,name,salary__c from Contacts) from Account where id IN : accIds]){
            a.Total_Salary__c=0;
            for(Contact con : a.Contacts){
                System.debug('con-->'+con        if(con.salary__c!=null){
                    a.Total_Salary__c = a.Total_Salary__c + con.salary__c;
                }            
            }
            lstAccToUpdate.add(a);
        }
        update lstAccToUpdate;


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


Test Class:

@isTest
public class AccountTrigger1TestClass {
static testMethod void test1(){
        Account acc = new Account();
        acc.Name = 'Test Account';
        acc.Number_of_Contacts__c = 3;
        insert acc;
    }
}

No comments:

Post a Comment