0

I written a trigger that inserts a custom junction object on opportunity and contact when an opportunity product record is created. I have created a before insert trigger and helper class for the junction object below. I am looking to get fields from the opportunity record and am unable to do this. The fields I am looking to get back are apprentice_name__c (lookup to contact) and Course__c (lookup to product2). Can someone help me get to the opportunity record from the id?

public class EnrolmentTriggerHandler {

public class MyException extends Exception {}

public static void updateEnrolment(List<Enrolment__c> enrolments, Map<Id, Enrolment__c> oldMap){


    for(enrolment__c en : (List<Enrolment__c>)Trigger.new){

        set<id>oppsid = new set<id>();

        if(!oppsid.contains(en.opportunity__c)){
            oppsid.add(en.opportunity__c);   
        }


        if(oppsid.size()>0){

            Map<ID, Opportunity> oppMap = new Map<ID, Opportunity> ([select id, apprentice_name__c, course__c from Opportunity where id in: oppsid]);
            list<opportunity> opps = new List<Opportunity>();

            for(opportunity o : opps){



            }


        }
    }      
}
}

1 Answer 1

2

Your code looks correct except the bracket part. And you are iterating opps which is empty as you have just initialize it. You need to modify your code like

set<id>oppsid = new set<id>(); //declare it outside for loop
for(enrolment__c en : (List<Enrolment__c>)Trigger.new){
    oppsid.add(en.opportunity__c);   
}
//close the for loop as we don't make query inside for loop
if(oppsid.size()>0){

    Map<ID, Opportunity> oppMap = new Map<ID, Opportunity> ([select id, apprentice_name__c, course__c from Opportunity where id in: oppsid]);
    //iterate on trigger and get Opportunity from map from trigger
    for(enrolment__c en : (List<Enrolment__c>)Trigger.new){
        Opportunity opp= oppMap.get(en.opportunity__c); //you can use the opportunity__c 
        //more code
    }

}

Read comments for more details.

0

You must log in to answer this question.

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