function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Monika BariczaMonika Baricza 

Trigger not being executed straight away

Hi All, 

I am new to Salesforce and I am trying to develop an application where I created a custom object called Commissions which is related to the Contact object via Master-Detail relationship (Contact being the master). I created a custom checkbox in the Contact object which should be checked if the Contact has the most commissions within the Account where they belong to. I created a rollup field for this. 
My task is to create a trigger which automatically checks the custom checkbox if the contact is the contact who has the most commissions. I managed to create a working trigger however it only seems to execute after I add a commission for the second time, even though they have the biggest commission after the first addition already. I assume it has something to do with when the trigger is triggered but I can't figure out how to correct the code. Any help is appreciated. 
Here is my code: 
trigger UpdateContactOnCommissionUpdate on Commission__c ( after insert, after update, before insert, before update) {
    double maxCommission=0;
    Id ContactId;
    Id AccId;
    for(Commission__c comm:Trigger.new){
        ContactId=comm.Contact_Name__c;
    }
    
    System.debug('Contact id: '+ContactId);
  
    List<Contact> contacts=[SELECT AccountId FROM Contact WHERE Id=:ContactId];
    System.debug('Account ID: '+contacts.get(0).AccountId);
    AccId=contacts.get(0).AccountId;
   
    List<Contact> contactsToUpdate = new List<Contact>{};
     
    for(Contact c:[SELECT Id, Total_Commission__c, Primary__c FROM Contact WHERE AccountID=:AccId]){
        if(c.Total_Commission__c>maxCommission){
            maxCommission=c.Total_Commission__c;
            contactsToUpdate.add(c);
            }
    } 
    System.debug('Maximum commission'+ maxCommission);
    for(Contact c:contactsToUpdate){
        if(c.Total_Commission__c==maxCommission)
            c.Primary__c=true;
        else
            c.Primary__c=false;
    }
    if(contactsToUpdate != null && !contactsToUpdate.isEmpty())
        Database.update(contactsToUpdate);
    
    
   
}

 
Best Answer chosen by Monika Baricza
paul diracpaul dirac
Hi Monica, you have to specify the context in which the trigger will be fired.
In your case the code is run :(after insert, after update, before insert, before update) so I think your trigger is actually fired on an after action.
You can easily do this by wrapping your code inside an if that specifyes the action in which your trigger must be fired, eg if the action must triggered BEFORE you insert the record just put your trigger body inside this:
 
if(Trigger.isBefore && Trigger.isInsert){

}
The result must be something like this:
 
trigger UpdateContactOnCommissionUpdate on Commission__c ( after insert, after update, before insert, before update) {
if(Trigger.isbefore && Trigger.isInsert){
  
  double maxCommission=0;
    Id ContactId;
    Id AccId;
    for(Commission__c comm:Trigger.new){
        ContactId=comm.Contact_Name__c;
    }
    
    System.debug('Contact id: '+ContactId);
  
    List<Contact> contacts=[SELECT AccountId FROM Contact WHERE Id=:ContactId];
    System.debug('Account ID: '+contacts.get(0).AccountId);
    AccId=contacts.get(0).AccountId;
   
    List<Contact> contactsToUpdate = new List<Contact>{};
     
    for(Contact c:[SELECT Id, Total_Commission__c, Primary__c FROM Contact WHERE AccountID=:AccId]){
        if(c.Total_Commission__c>maxCommission){
            maxCommission=c.Total_Commission__c;
            contactsToUpdate.add(c);
            }
    } 
    System.debug('Maximum commission'+ maxCommission);
    for(Contact c:contactsToUpdate){
        if(c.Total_Commission__c==maxCommission)
            c.Primary__c=true;
        else
            c.Primary__c=false;
    }
    if(contactsToUpdate != null && !contactsToUpdate.isEmpty())
        Database.update(contactsToUpdate);
    
}    
   
}

Consider to put your trigger logic in a TriggerHandler class also.
See salesforce best practices for triggers in order to achive this:
https://developer.salesforce.com/page/Apex_Code_Best_Practices
 

All Answers

Bhawana Mehta SFDCBhawana Mehta SFDC
Hi Monika,

can you try removing beforre Insert and before update from trigger. Scenario that you meantioned is only applicable for after update. Plz run it after changes and let me know if still facing issue.
paul diracpaul dirac
Hi Monica, you have to specify the context in which the trigger will be fired.
In your case the code is run :(after insert, after update, before insert, before update) so I think your trigger is actually fired on an after action.
You can easily do this by wrapping your code inside an if that specifyes the action in which your trigger must be fired, eg if the action must triggered BEFORE you insert the record just put your trigger body inside this:
 
if(Trigger.isBefore && Trigger.isInsert){

}
The result must be something like this:
 
trigger UpdateContactOnCommissionUpdate on Commission__c ( after insert, after update, before insert, before update) {
if(Trigger.isbefore && Trigger.isInsert){
  
  double maxCommission=0;
    Id ContactId;
    Id AccId;
    for(Commission__c comm:Trigger.new){
        ContactId=comm.Contact_Name__c;
    }
    
    System.debug('Contact id: '+ContactId);
  
    List<Contact> contacts=[SELECT AccountId FROM Contact WHERE Id=:ContactId];
    System.debug('Account ID: '+contacts.get(0).AccountId);
    AccId=contacts.get(0).AccountId;
   
    List<Contact> contactsToUpdate = new List<Contact>{};
     
    for(Contact c:[SELECT Id, Total_Commission__c, Primary__c FROM Contact WHERE AccountID=:AccId]){
        if(c.Total_Commission__c>maxCommission){
            maxCommission=c.Total_Commission__c;
            contactsToUpdate.add(c);
            }
    } 
    System.debug('Maximum commission'+ maxCommission);
    for(Contact c:contactsToUpdate){
        if(c.Total_Commission__c==maxCommission)
            c.Primary__c=true;
        else
            c.Primary__c=false;
    }
    if(contactsToUpdate != null && !contactsToUpdate.isEmpty())
        Database.update(contactsToUpdate);
    
}    
   
}

Consider to put your trigger logic in a TriggerHandler class also.
See salesforce best practices for triggers in order to achive this:
https://developer.salesforce.com/page/Apex_Code_Best_Practices
 
This was selected as the best answer
Monika BariczaMonika Baricza
Hi all, 

I actually got the solution in the meanwhile. I forgot to consider the new commission that is being entered to calculate the maxmimum value. 
At the end my code looks like this and it is working (I will 100% have a look at the links I got from you though)
Thank you very much for your help

Monika
trigger UpdateContactOnCommissionUpdate on Commission__c ( after insert, after update, before insert, before update) {
    double maxCommission=0;
    Id ContactId;
    Id AccId;
    Double currentCommission;
    for(Commission__c comm:Trigger.new){
        ContactId=comm.Contact_Name__c;
        currentCommission=comm.Commission_Amount__c;
    }
    
    System.debug('Contact id: '+ContactId);
  
    List<Contact> contacts=[SELECT AccountId FROM Contact WHERE Id=:ContactId];
    System.debug('Account ID: '+contacts.get(0).AccountId);
    AccId=contacts.get(0).AccountId;
   
   //Contacts to be updated
    List<Contact> contactsToUpdate = new List<Contact>{};
    Contact currentMaxContact;
    for(Contact c:[SELECT Id, Total_Commission__c, Primary__c, Name FROM Contact WHERE AccountID=:AccId]){
        if(c.Total_Commission__c>maxCommission){
            maxCommission=c.Total_Commission__c;
            currentMaxContact=c;
            }
    }
    System.debug('Current max: '+currentMaxContact.Name) ;
    contactsToUpdate.add(currentMaxContact);
    
     //finding the maximum commission
    for(Contact c:[SELECT Id, Total_Commission__c, Primary__c, Name FROM Contact WHERE AccountID=:AccId]){
        if(c.Total_Commission__c+currentCommission>maxCommission && c.Id==ContactId){
            maxCommission=c.Total_Commission__c+currentCommission;
            System.debug('current is the biggest: '+maxcommission);
            contactsToUpdate.add(c);
            }
            else if(c.Total_Commission__c>maxCommission && c.Id!=ContactId){
            maxCommission=c.Total_Commission__c;
            System.debug('other one is the bigger: '+maxcommission);
            contactsToUpdate.add(c);
            }
    } 
    System.debug('Maximum commission'+ maxCommission);
   
    for(Contact c:contactsToUpdate){
    System.debug('Contacts to update: '+c.Name);
    if(c.Id!=ContactId){
        if(c.Total_Commission__c==maxCommission)
            c.Primary__c=true;
        else
            c.Primary__c=false;
    }
    if(c.Id==ContactId){
        if(c.Total_Commission__c+currentCommission==maxCommission)
            c.Primary__c=true;
        else
            c.Primary__c=false;
    }
    }
    
    if(contactsToUpdate != null && !contactsToUpdate.isEmpty())
        Database.update(contactsToUpdate);
    
    
   
}

 
paul diracpaul dirac
Here to help ;)