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
Keith Stephens 18Keith Stephens 18 

Trigger to update email

Hello All,
I am new at using Salesforce and trying to learn it.
I want to have a trigger fire on "after insert" or "after update" when the user select a broker name upon saving I want to update the broke email address.
Below is my trigger, but nothing happens, I don't know what is wrong.
trigger PopulateBrokerEmail on Case (after insert, after update) {
    try {   
       
        if(trigger.isAfter){
            Case c1;
                if(c1.AccountBroker__c != ''){
                   c1.Broker_Email__c = c1.AccountBroker__r.Primary_Email__c;
                }
                
           //for(Case c1 : trigger.new){
           //     if(c1.AccountBroker__c != ''){
           //        c1.Broker_Email__c = c1.AccountBroker__r.Primary_Email__c;
           //     }
           }
        }
        catch(Exception e) {
            //Package suspended, uninstalled or expired, exit gracefully.
            System.debug('PopulateBrokerEmail');
        }
}

Thanks,
Naveen Rahul 22Naveen Rahul 22
Hello Kieth,

their is no DML operation will take place at after Insert ,After update.
it has to be before insert,before update
 
trigger PopulateBrokerEmail on Case (before insert, before update) {
    try{   
         if(trigger.isBefore){
           for(Case c1 : trigger.new){
                system.debug('=====>'+c1);           
                if(c1.AccountBroker__c!= NULL){
                
                   Account_Broker__c somevalue=[select Primary_Email__c from Account_Broker__c where Id=:c1.AccountBroker__c];
                   
                   system.debug(c1.AccountBroker__r.Primary_Email__c+'=====>');         
                   c1.Broker_Email__c = somevalue.Primary_Email__c;
                }
           }
        }
    }catch(Exception e){
       //Package suspended, uninstalled or expired, exit gracefully.
       System.debug('PopulateBrokerEmail');
    }
    
}


i think you wont be updating the more than 100 Cases in Dataloader or Any other data Manupulation Tool. So using a query wont hurt.
else collect it in MAP and query the primary email from it.


Thanks
D Naveen Rahul.
Keith Stephens 18Keith Stephens 18
Thanks D Naveen Rahul,
But the Select query does not work, it generates an error:
"sObject type 'Account_Broker__c' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names."

I have tried to change it to use "c1.Account_Broker__r" and just Account_Broker__r, but these did not work either.
So I want to get the primary email of the parent and set the broker_email of the case.
Case.Broker_Email__c = Case.Account_Broker__r.Primary_Email__c.
Thanks,
Keith.