+ Start a Discussion
BrandiTBrandiT 

Need Trigger to Update Lookup Field on Account when New Account Created

Hello,

I need a simple trigger that will populate a lookup field on my Account object called Grouping__c (looks up to custom Client_Group__c object).

 

When an account is created or updated and the Grouping__c lookup field is not populated, I need the trigger to automatically populate it with a specific Client_Group__c record, named UNGROUPED.

 

I cannot figure out how to write the trigger without referencing the specific record id for the UNGROUPED record.

 

Here is what I have started (which is totally wrong), but I've tried it several ways with no luck.

 

Can someone help me re-write this please?  I know it can't be that hard to write, but I'm going in circles with it.

 

trigger AutoCltGroup on Account (before insert, before update) {
  LIST<Client_Groups__c> CGs = [Select ID From Client_Groups__c
          Where Name='UNGROUPED']; 
 
  for (Account a : Trigger.new) {
    if(a.Client_Group__c==null){
      a.Client_Group__c = 'a0F70000005bzBa';    --this is what I want to avoid (hardcoding the id into the trigger)
    }
  }
}

Best Answer chosen by Admin (Salesforce Developers) 
BrandiTBrandiT

oops spoke to soon!  I got it to work by changing the last part to CGs.id

 

Thanks again!

All Answers

DharmeshDharmesh

do something like this

 

trigger AutoCltGroup on Account (before insert, before update) { 
  Client_Groups__c CGs = [Select ID From Client_Groups__c  Where Name='UNGROUPED' limit 1];  
  
  for (Account a : Trigger.new) { 
    if(a.Client_Group__c==null){
      a.Client_Group__c =CGs;
    }
  }
}

BrandiTBrandiT

I tried that, but got the error message:

 

 Error: Compile Error: Illegal assignment from SOBJECT:Client_Groups__c to Id at line 6 column 7 

 

Any idea what it's telling me?

 

Thanks!

Brandi

BrandiTBrandiT

oops spoke to soon!  I got it to work by changing the last part to CGs.id

 

Thanks again!

This was selected as the best answer