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
adiazadiaz 

Help with Apex Code - Before Update

Hello,

 

I began writing an apex that auto populates fields in my case based on a lookup field before saving (hope that made sense :) ).

 

My lookup field relates the case to an account by account number. I have some field such as main contact, phone, address, etc. that I would like to auto populate once the lookup field is populated before submitting/saving.

 

Is this possible with a Before Update? Can someone help me out with the first few lines? Thanks!

 

 

frederic baudaxfrederic baudax

Hi,

 

Here is a sample you can use, didn't test it but you should understand the logic to use. Also you can only use "before insert/update" since you make changes to the record you work on which becomes read only at "after insert/update" stage.

 

 

trigger Case_Tr_Gatheraccountdata on Case (before insert, before update) {

//create the containers you will need
  List<Id> Accounts = new List<Id>{};
  Map<Id,Case> Casestoupdate = new Map<Id,Case>{};

  // Gather the ids to build your query and make sure you will find something. By doing it this way, even with bulk inserts/updates you will not hit the soql governor limit (21)
  for(Case c: Trigger.new){
    if (c.AccountId != NULL )  {
      Accounts.add(c.AccountId);
    }
  }
  // Find the data (change the field names to match all the data you need!)
  // only query if there is at least 1 record 
  If (Accounts.size() > 0){
  Account[] accts = [SELECT  Id, contact, phone, address from Account WHERE Id IN :Accounts];
  for(Account a : accts){
     if (a.Id != NULL ){
//put it all in a map for later use
Casestoupdate.put(a.AccountId, a);
     }
  }
  }
for (Case c: Trigger.new){
// loop back trough 
// make sure you found something first
if(Casestoupdate.containsKey(c.AccountId)){
//map your fields on the fly
    c.field = Casestoupdate.get(c.AccountId).accountfield;
    c.field2 = Casestoupdate.get(c.AccountId).accountfield2;
//etc... 
//no update statement needed since you are in a before update trigger
} } }

 Cheers,

Fred.