+ Start a Discussion
brozinickrbrozinickr 

Populate custom ParentID in lookup on Child trigger

I was wondering if someone would be able to help me with this.

 

I am trying to build a trigger that will populate the appropriate AL_Goal__c id in a lookup field on Opportunity to connect the two objects.  I am trying to connect the two based of the OwnerID and Date (Year_Month__c needs to equal the same month and year of the CloseDate, and assign the appropriate Goal to the opportunity based on the date).

 

So for example, I create an opportunity with a close date of 91/2013.  When I save, it should populate the lookup field on the opportunity with the id of AL_Goal__c with Year_Month of 2013-9 and OwnerID is my user Id.

 

This is what I have so far, but I am confused on how to connect the Opportunities and AL_Goal__c together.  I figured I would have to create two lists like this and do some sort of a map, but I am not entirely sure on how to go about doing this:

 

List <Opportunity> oppids = [SELECT Id, OwnerID, CloseDate, AL_Goal__c from Opportunity];
List <AL_Goal__c> goals = [SELECT Id, Year_Month__c, OwnerID from AL_Goal__c];

 

 

 

 

trigger UpdateOpportunityGoalLookUp on Opportunity (before insert, before update) 
{
    //instantiate set to hold unique AL_Goal record ids
    Set<Id> GoalIds = new Set<Id>();
    
    for(Opportunity o : Trigger.new)
    {
        GoalIds.add(o.AL_Goal__c);
    }

    //instantiate map to hold AL_Goal record ids to their corresponding ownerids
    Map<Id, AL_Goal__c> AL_GoalMap = new Map<Id, AL_Goal__c>([SELECT Id FROM AL_Goal__c WHERE Id IN: GoalIds]);

    for (Opportunity o : Trigger.new) 
    {
        if (o.AL_Goal__c == null && AL_GoalMap.containsKey(o.AL_Goal__c)) 
        {
            o.AL_Goal__c = AL_GoalMap.get(o.Id).Id;
        }
    }
}

 

gbu.varungbu.varun

I think this error is due to if condition

 

 for (Opportunity o : Trigger.new) 
    {
        if (o.AL_Goal__c == null && AL_GoalMap.containsKey(o.AL_Goal__c)) 
        {
            o.AL_Goal__c = AL_GoalMap.get(o.Id).Id;
        }
    }

if AL_Goal__c is null and you are getting it for GoalMap.containsKey. You are finding GoalMap for null values. I think you should check 

if (o.AL_Goal__c != null && AL_GoalMap.containsKey(o.AL_Goal__c))