[SalesForce] Cannot populate field value on new record with trigger

I am trying to write a simple trigger that will populate field values on a newly created record.

I'm using standard objects: Account and Opportunity

I have two custom fields on the Account object called ChiefTechOwner__c and ComputerLocation__c. I've also added these fields on the Opportunity object.

What I need is when a new Opportunity record is created (and an Account Name for that opportunity is selected), I need a trigger to get the corresponding values for the ChiefTechOwner__c and ComputerLocation__c fields associated with that given Account, and populate it on the Opportunity record.

I've written the code below.
The "Before Insert" returns null because it is querying for ID's that are not yet created. I changed it to "After Insert", but then I get a "read-only" error.

If feel like it is a common scenario; can someone help me understand how to solve this problem?

trigger UpdOppty on Opportunity (before insert) {

Map<Id,Account> relatedAccounts = new Map<Id,Account>(
    [Select Id, ComputerLocation__c, ChiefTechOwner__c
        FROM Account
        WHERE Id 
        IN (Select AccountId 
                FROM Opportunity
                WHERE Id = :Trigger.new)
     ]
     );

for (Opportunity o : Trigger.new) {

 for (Account a : relatedAccounts.values()) {

   if (a.Id == o.AccountId) {

     o.ChiefTechOwner__c = a.ChiefTechOwner__c;
     o.ComputerLocation__c = a.ComputerLocation__c; 
   }
 }

}
}

Best Answer

Your close, use a Map with the account ID from the Opportunity Records

trigger UpdOppty on Opportunity (before insert) {


    Map<Id,Account> relatedAccounts = new Map<Id,Account>();

    for (Opportunity o : Trigger.new) {
        relatedAccounts.put(o.AccountId,null);
    }

    relatedAccounts = New Map<ID,Account>([Select Id, ComputerLocation__c, ChiefTechOwner__c From Account Where Id In :relatedAccounts.keySet()]);

    for (Opportunity o : trigger.new) {
        Account a = relatedAccounts.get(o.AccountId);
        o.ChiefTechOwner__c = a.ChiefTechOwner__c;
        o.ComputerLocation__c = a.ComputerLocation__c; 

    }
}
Related Topic