0

I have an object - "training" , which has a master detail relationship with an object - "Employee". I am writting a trigger on training such that when a new training record is created for an employee, it should create an object called "Log" which should copy a field of employee into a field in "Log" object:

for(trainig__c training: trigger.new){

List<Log__c> newtransLog = new List<Log__c>();
        Transaction_Log__c log = new Transaction_Log__c(Job_Level_Name__c=training.Employee__r.Job_Level_Name__c);
        newtransLog.add(log);
}
Insert newtransLog;

What I am trying to do is - get a value of field from Employee record and assign it to a field in Log record. But this seems to be not working, I am getting a blank value for Job_Level_Name__c in the Log record

PS - Not sure how I shall query the parent fields inside the for loop? How do I do the query and assignment in this case?

2
  • Not sure how I shall query the parent fields inside the for loop? How do I do the query and assignment in this case?
    – SfdcBat
    Aug 2, 2016 at 19:17
  • 1
    It's literally in the Apex Code Best Practices doc. See #9.
    – Adrian Larson
    Aug 2, 2016 at 20:52

1 Answer 1

1

See Apex Code Best Practices:

Best Practice #9: Writing Test Methods to Verify Large Datasets

...

trigger contactTest on Contact (before insert, before update) {
    
    Set<Id> accountIds = new Set<Id>();
    for(Contact ct: Trigger.new)
        accountIds.add(ct.AccountId);
    
    //Do SOQL Query      
    Map<Id, Account> accounts = new Map<Id, Account>(
        [select id, name, billingState from Account where id in :accountIds]);
    
    for(Contact ct: Trigger.new){
        if(accounts.get(ct.AccountId).BillingState=='CA'){
            System.debug('found a contact related to an account in california...');
            ct.email = '[email protected]';
            //Apply more logic here....
        }
    } 
    
}

You must log in to answer this question.

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