APEX TRIGGER

SCENARIO 1:- Fetch Total Related List Record on Parent With MAX Salary in Apex Salesforce

This Trigger will help to calculate Number of Employees with Max Salary from Employee on Account record. For this approach i have used aggregate method to get MAX salary and use Count for number of employee.

trigger EmployeeInfo on Employe__c (After insert, After Update, After Delete, After Undelete) {

    List<Employe__c> empList = Trigger.isDelete?Trigger.Old:trigger.New;

    Set<Id> accIds = new Set<Id>();
    for(Employe__c emp : empList){
        if(emp.Account__c != null){
            accIds.add(emp.Account__c);
            if(Trigger.IsUpdate){
                // below criteria will check if user change the parent like Account then Calculation will update on Old Parent
                if(trigger.OldMap.get(emp.Id).Account__c != emp.Account__c ){
                    accIds.add(trigger.OldMap.get(emp.Id).Account__c);
                }
            }
        }
        	
    }   
    
    
    AggregateResult[] agrResult = [Select Account__c, COUNT(Id)totalEmp, Max(Salary__c)MaxSal from Employe__c Where Account__c IN: accIds
                                         GROUP BY Account__c];
    Map<Id, Account> accMap = New Map<Id, account>([Select Max_Salary__c,Total_Employee__c From Account Where Id IN: accIds]);

    for(AggregateResult agr : agrResult){
        accMap.get((Id)agr.get('Account__c')).Max_Salary__c = (Decimal)agr.get('MaxSal');
        accMap.get((Id)agr.get('Account__c')).Total_Employee__c = (Integer)agr.get('totalEmp');
    }
    if(accMap.size() > 0)
        update accMap.values();    
}

SCENARIO 2:- Write a Trigger to update Opportunity total amount on related Account:-

trigger rollupOpportunity on Opportunity (after insert, after update,after delete, after undelete) 
{
    set<id> accid = new set<id>() ;

    List<Opportunity> oppList = Trigger.isDelete ? Trigger.old : Trigger.New;
    
for(Opportunity opp : oppList){
   if(opp.AccountId != null){
      accid.add(opp.AccountId);
   }
 }
    
    list<account> acco = new list<account>();
    acco = [Select id, name ,(SELECT id, name, Amount FROM opportunities ) From account Where id=:accid];
    
    list<account> acctoupdate = new list<account>();
    for(account acc:acco)
    {
       acc.opportunity_count__c = acc.opportunities.size();
        
        decimal sum = 0.0;
        
        for ( opportunity opp : acc.opportunities)
        {
            
            System.debug('opp.Amount== '+opp.Amount);
            sum = sum + opp.Amount ;
        }
        acc.Total_opportunity_Amount__c = sum;
        acctoupdate.add(acc);
    }
    
    update(acctoupdate);
}

SCENARIO 3: Create a trigger that’s prevent to insert duplicate contacts

Trigger preventDuplication on contact(before insert, before update) {
Set<string> nameSet = new Set <string>() ;
If (trigger.IsBefore) {
    If(trigger. Is Insert || trigger.IsUpdate){
        For(Contact con : trigger.new){
                  NameSet.add(con.lastName);
               } 
           } 
      } 

List<Contact> lstcon = [select Id, lastName from Contact where lastName in :nameSet];

For(Contact con2 : trigger.new){
   If(lstcon.size()>0){
       con2.lastName.adderror('duplicate last name found');
   }
​​​​​​} 

SCENARIO 4: Add Page number on contact record page, if any contact goes to delete then page count will change

trigger UpdateConatctPageNumber on Contact (After insert, After Update, After Delete,After UnDelete ) {
    
    
    List<Contact> conList = Trigger.isDelete ? Trigger.old : trigger.new;
    Set<Id> accIds = new Set<Id>();
    for(Contact con: conList){
        if(con.AccountId != null){
            accIds.add(con.AccountId);
        }
    }
    
    Map<Id, Contact> mapContact = new Map<Id,Contact>([Select Id, dotsquaremukesh__PageNumber__c from Contact where AccountId IN: accIds]);
    
    Integer count = 0;
    for(Contact con : conList){
        if(Trigger.IsInsert || Trigger.IsUnDelete){
            if(!AccountProcessor.isRunOnce){
                mapContact.get(con.id).dotsquaremukesh__PageNumber__c =+ mapContact.size(); 
            }
            
        }else if(Trigger.IsDelete){
            Integer count = 0;
            for(Contact conItem : mapContact.values()){
                count++;
                conItem.dotsquaremukesh__PageNumber__c = count;
            }
                    
           }
    }
    
    if(mapContact.size() > 0 && !AccountProcessor.isRunOnce){
        AccountProcessor.isRunOnce = true;

        update mapContact.values();   
    }
        
        

}

SCENARIO 5:- Write a trigger on the Account when the Account is updated check all opportunities related to the account. Update all Opportunities Stage to close lost if an opportunity created date is greater than 30 days from today and stage not equal to close won.

trigger OppoStageUpdate on Account (after update){
Set<Id> accountIds = new Set<Id>();
for(Account a:Trigger.new){
accountIds.add(a.Id);
}
//day30 is the date which is 30 days less than today
DateTime day30=system.now()-30;
List<Opportunity> oppListToUpdate=new List<Opportunity>();
//getting the opportunities whose account has been updated
List<Opportunity> oppList = [Select Id, AccountId, StageName, CreatedDate, CloseDate from Opportunity where AccountId in :accountIds];
if(oppList.size()>0){
for(Opportunity opp : oppList){
//checking for condition if created date is greater than 30 days from today and stage not equal to close won
if(opp.CreatedDate<day30 && opp.StageName!='Closed Won'){
opp.StageName='Closed Lost';    //This is a mandatory field when we update the CloseDate
opp.CloseDate=system.today();
oppListToUpdate.add(opp);  //putting the changed opportunity to separate list to update later
}
}
}
//checking if the opportunity list which has changed is having records or not
if(oppListToUpdate.size()>0){
update oppListToUpdate;
}
}

SCENARIO 6:

Create a Custom field called “Number of Locations” on the Account Object (Data Type=Number). The following trigger creates the number of contacts that are equal to the number which we will enter in the Number of Locations field on the Account Object

trigger ContactsCreation on Account (after insert)

{
 list<contact> listContact = new list<contact>();
 map<id,decimal> mapAcc=new map<id,decimal>();
 for(Account acc:trigger.new){
 mapAcc.put(acc.id,acc.Number_of_Locations__c);
 }
 if(mapAcc.size()>0 && mapAcc!=null){
 for(Id accId:mapAcc.keyset()){
 for(integer i=0;i<mapAcc.get(accId);i++){
 contact newContact=new contact();
 newContact.accountid=accId;
 newContact.lastname='contact'+i;
 listContact.add(newContact);
 }
 }
 }
 if(listContact.size()>0 && listContact!=null)
 insert listContact;
 }

SCENARIO:- 7

Create the object called “Customer Project” and create a Status field under this object with the picklist data type (Values=Active, Inactive). Create the relationship between this custom object and Opportunity so that the Customer Project is a related list to the Opportunity. Create  Active Customer project‑ field on Opportunity object (Data Type=Checkbox) The logic is when we create Customer Project for an Opportunity with the Status=Active, then Active Customer project check box on the Opportunity Detail page is automatically checked.

trigger UpdateCPActivenOnOppty on Customer_Project__c (after insert)
 {
 List<Opportunity> opps=new List<Opportunity>();
 for(Customer_Project__c cp:Trigger.New){
 if(cp.Status__c=='Active'){
 Opportunity opp= new Opportunity(id=cp.Opportunity__c);
 opp.Active_Customer_Project__c = True;
 opps.add(opp);
 }
 }
 update opps;
 }

SCENARIO: 8 When we create the Account record, the Account Owner will be automatically added to Sales Rep field. When we update the Account owner of the record, then also the Sales Rep will be automatically updated.

triggerUpdateSalesRep on Account (Before insert,Before Update)

{
 Set<Id>setAccOwner=new Set<Id>();
 for(Account Acc: trigger.new)
 {
 setAccOwner.add(Acc.OwnerId);
 }
 Map<Id,User>User_map = new Map<Id,User>(“select Name from User where id
 in:setAccOwner”);
 for(Account Acc: Trigger.new)
 {
 User usr=User_map.get(Acc.OwnerId);
 Acc.sales_Rep1__c=usr.Name;
 }
 }

9. Create a trigger on Account object that’s will Prevent the users to create Duplicate Accounts by account name

trigger AccountDuplicateTrigger on Account (before insert, before the update)
{
 for(Account a:Trigger.new)
 {
 List<Account> acc="Select id from Account where Name=:a.Name and Rating=:a.Rating";
 if(acc.size()>0)
 {
 acc.Name.addError('You Cannot Create the Duplicate Account');
}
}
}

10. Write a trigger that’s prevent the users from deleting the Accounts.

trigger AccountDelete on Account (before delete)

{
 for(Account Acc:trigger.old)
 {
 acc.adderror('You Cannot Delete the Account Record');
 }
 }

11. Create a Custom field called “Number of Locations” on the Account Object (Data Type=Number)

The following trigger creates the number of contacts that are equal to the number which we will enter in the Number of Locations field on the Account Object

trigger ContactsCreation on Account (after insert)

{
 list<contact> listContact = new list<contact>();
 map<id,decimal> mapAcc=new map<id,decimal>();
 for(Account acc:trigger.new){
 mapAcc.put(acc.id,acc.Number_of_Locations__c);
 }
 if(mapAcc.size()>0 && mapAcc!=null){
 for(Id accId:mapAcc.keyset()){
 for(integer i=0;i<mapAcc.get(accId);i++){
 contact newContact=new contact();
 newContact.accountid=accId;
 newContact.lastname='contact'+i;
 listContact.add(newContact);
 }
 }
 }
 if(listContact.size()>0 && listContact!=null)
 insert listContact;
 }