I have a custom object in salesforce. Every record has many fields. One is a lookup field in which we select an opportunity from lookup. What we want is another lookup field: Account__c which has to be automatically populated with account name of that respective opportunity.

In the code below, "After insert" is working but before update is not working properly.

 trigger trigger_name on object__c (after insert, before update) {

    List<object__c> listOfSfdcRecords  =[SELECT Opportunity__r.AccountId,Opportunity__r.Account.Name FROM object__c WHERE ID IN :trigger.newMap.keySet()];
    Map<String, Id> myMap = new Map<String, Id>(); 
    for(object__c eachRec : listOfSfdcRecords){
        myMap.put(eachRec.Id, eachRec.Opportunity__r.AccountId);
        List <object__c> updateList = new List <object__c>();
        for(object__c eachSfdc: listOfSfdcRecords){
            object__c sfdc = new object__c(Id = eachSfdc.Id);
            sfdc.Test_Account__c = eachSfdc.Opportunity__r.AccountId;
        update updateList;
        for(object__c eachSfdc: trigger.new){
            //System.debug('before update'+eachSfdc.Opportunity__r.AccountId);
            System.debug('b4 update'+myMap.get(eachSfdc.id));
            eachSfdc.Test_Account__c = myMap.get(eachSfdc.id);

  • Do you need a lookup field populated or just the name on the Account? You could get the name via formula field.
    – Mike Chale
    Commented Dec 2, 2013 at 13:42
  • @MikeChale yes Mike using a formula field is easy and earlier i was using a formula field for this but i want it to be lookup ,and that too autopopulated.
    – James
    Commented Dec 9, 2013 at 9:01

2 Answers 2


You can do something like this. Basically you would need to get the opportunities of all the records that you're inserting / updating, get the associated accounts and then set the account values in the customOject's account__c field.

trigger autoPopulateTrigger on customObject__c (before insert, before update){

    //get the oppotyunity Id's and store it in a set.
    set<Id> opptyIdSet = new set<Id>();
    for(customObject__c co: trigger.new){
        if(co.opportuntiy__c != null){

    //query the opportunity records and get the associated accounts.
    map<id, opportunity> opptyMap = new map<id, opportunity>{[SELECT id, accountid from opportunity where Id IN: opptyIdSet]};

    //update the account value based on the opportunity in the record.
    for(customObject__c co: trigger.new){
            co.Account__c = opptyMap.get(co.opportunity__c).accountId;

  • Hi, Thanks for you r answer . I did similar thing but error comes up like this: Error: Invalid Data. Review all error messages below to correct your data. Apex trigger trig_name caused an unexpected exception, contact your administrator: Custom_obj: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.trig_name: line 17, column 1
    – James
    Commented Dec 3, 2013 at 8:52
  • can you edit and update your question with the code that you have used?
    – Sam
    Commented Dec 3, 2013 at 9:06
  • I have followed ur code but previously i did was something like in which on ly after insert was working ,not before update::
    – James
    Commented Dec 3, 2013 at 9:15
  • you could edit your question and update it code in it.. Or can you put the line#17 in the comment?
    – Sam
    Commented Dec 3, 2013 at 10:52
  • Rest code is same as yours :Error coming up in this line.. co.Test_Account__c=Oppmap.get(co.opportunity__c).AccountId;
    – James
    Commented Dec 3, 2013 at 10:55

What no Declarative Solution? Ideally you would be to use Workflow Field Update to do this declaratively, however it is not possible with fields of Lookup type currently. There seems to be an Idea raised for it, with surpassingly a low number of votes.

Apex Trigger Solution. The only workaround is to write an Apex Trigger (and associated Apex Test class) to do this. You will need to understand some concepts in order to start with Apex, the Apex Developers Guide has some great introductory sections, as well as these on Apex Triggers.

The basic steps in your trigger will be as follows.

  1. Loop over the Trigger.new list and store in a Set list all the related Opportunity Id's.
  2. Query the Account field on the Opportunities object and store the result in a Map
  3. Loop over the Trigger.new list again and use the Map created in step 1 to determine the Account to populate in your Account field
  • He may also need a trigger on Opportunity Update, in case the Lookup to Account is updated so data is kept in sync
    – ManSpan
    Commented Dec 2, 2013 at 11:29
  • The logic is the same for update as it is for insert. Just ensure your trigger is defined to capture these trigger events, as per the example shown in the other answer. Commented Dec 2, 2013 at 11:30
  • The new Process Builder finally supports updating lookup fields without using Apex. Commented Jun 16, 2015 at 21:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .