+ Start a Discussion
shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com 

Create Map of Opportunity Team Member and Opportunity Close Date

Hi Everyone,
             I have a requirement with me . I need to do a validation when opportunity team member is added to the opportunity. The requirement is that , user must not be able to add a new opportunity team member on an opportunity which has its close date in the past . I have written a before insert trigger on Oppotunity team member . Need your help in getting SOQL out of for Loop. I know it can be done via map , just need some pointers to get started on this.

Sample code:

for(OpportunityTeamMember member : Trigger.new)
      {
        Opportunity opp= Select CloseDate from Opportunity where Id = member.OpportunityId ;
        if (opp.closedate<system.today()){
         member.adderror('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
        }
      }
Best Answer chosen by shrey.tyagi88@tcs.com
Nayana KNayana K
Map<Id, Date> mapOppIdToCloseDate = new Map<Id, Date>();
for(OpportunityTeamMember member : Trigger.new)
{
    mapOppIdToCloseDate.put(member.OpportunityId, null);
}

for(Opportunity objOpp : [SELECT Id, CloseDate FROM Opportunity WHERE Id IN : mapOppIdToCloseDate.keySet()])
{
    mapOppIdToCloseDate.put(objOpp.Id, objOpp.CloseDate);
}

for(OpportunityTeamMember member : Trigger.new)
{
    if(mapOppIdToCloseDate.get(member.OpportunityId) < System.today())
    {
        member.addError('ERROR MSG');
    }
}

All Answers

Nayana KNayana K
Map<Id, Date> mapOppIdToCloseDate = new Map<Id, Date>();
for(OpportunityTeamMember member : Trigger.new)
{
    mapOppIdToCloseDate.put(member.OpportunityId, null);
}

for(Opportunity objOpp : [SELECT Id, CloseDate FROM Opportunity WHERE Id IN : mapOppIdToCloseDate.keySet()])
{
    mapOppIdToCloseDate.put(objOpp.Id, objOpp.CloseDate);
}

for(OpportunityTeamMember member : Trigger.new)
{
    if(mapOppIdToCloseDate.get(member.OpportunityId) < System.today())
    {
        member.addError('ERROR MSG');
    }
}
This was selected as the best answer
shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com
Thanks Nayana!!!