[SalesForce] Trigger to autopopulate a lookup field via related record

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){
        System.debug(listOfSfdcRecords);          
        myMap.put(eachRec.Id, eachRec.Opportunity__r.AccountId);
    }
    if(trigger.isAfter){
        List <object__c> updateList = new List <object__c>();
        for(object__c eachSfdc: listOfSfdcRecords){
            System.debug(eachSfdc.Opportunity__r.AccountId);
            object__c sfdc = new object__c(Id = eachSfdc.Id);
            sfdc.Test_Account__c = eachSfdc.Opportunity__r.AccountId;
            updateList.add(sfdc);
        }
        update updateList;
    }
    if(trigger.isBefore){
        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);
        }
    }

}

Best Answer

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){
            opptyIdSet.add(co.opportunity__c);
        }
    }

    //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){
        if(opptyMap.containsKey(co.opportunity__c)){
            co.Account__c = opptyMap.get(co.opportunity__c).accountId;
        }       
    }

}