0

We have a Case related to an Opportunity, and whenever a particular Case is created with any of 3 specific stages, it should send an email to the opportunity Account manager regarding the changes in the case. My code is working, but we wanted to use a Mapto get rid of the second for loop. Is it possible? If so, how?

Public static void SendEmailtoAMsInsert(list<Case> NewCaseLst){

    //when new case is created
    List<user> Amuserid= new list<user>();
    Amuserid = [select id from user where id in (select userorgroupid from groupmember where group.name='EU AMS alerts')];
    Set<id> userSetIds=new Set<id>();
    List<user> user =  new List<user>();
    Set<Id> setRTIds = StaticFactory.getRecordTypeIdsByName(new Set<string>{'YuMe Trafficking','YFA Trafficking'});

    for(User u: Amuserid){
        userSetIds.add(u.Id);
    }
    system.debug('###UserIds::'+userSetIds);

    List<Id> LstId = new List<Id>();
    for(case cs: NewCaseLst){
        LstId.add(cs.Opportunity__c);
    }

    List<Opportunity> OppId = [select id,Name,YuMe_Transaction_number__c from Opportunity where ID =: LstId];
    //code ends

    for(case cs: NewCaseLst){
        for(opportunity opp: OppId){ //*** Using MaP??? ****//
            if(setRTIds.contains(cs.RecordTypeId)){
                system.debug('###cs.Stage__c::'+cs.Stage__c.contains('Media: YFA MA Ready for Trafficking'));
                system.debug('###cs.Stage__c::'+cs.Stage__c.contains('Media: YFA MA Ready for Trafficking'));
                system.debug('###cs.Stage__c::'+cs.Stage__c.contains('Media: Awaiting Action from YFA-MS'));
                system.debug('###UserIds::'+userSetIds.contains(cs.Account_Manager__c));

                if((
                    cs.Stage__c.contains('Media: YFA Revised MA Ready for Trafficking') ||
                    cs.Stage__c.contains('Media: YFA MA Ready for Trafficking') ||
                    cs.Stage__c.contains('Media: Awaiting Action from YFA-MS'))
                    && userSetIds.contains(cs.Account_Manager__c)){

                    system.debug('###yes::');

                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                    string[] address = new string[]{cs.Account_Manager__c};
                    email.setToAddresses(address);

                    string subject = 'P'  +cs.Priority__c+'-'+opp.YuMe_Transaction_number__c+ '-'+cs.Stage__c +' for '+opp.Name;
                    email.setSubject(subject);
                    email.setPlainTextBody(
                    'Hi,'+
                    '\n'+
                    '\n  An action item is pending from you and is detailed in the Case Comments. Please update the stage accordingly when this is available.'+
                    '\n'+
                    '\n This is notify that the case Stage:' + cs.Stage__c+
                    '\n'+
                    '\n Case Number:'+Cs.CaseNumber+
                    '\n'+
                    '\n Case Subject:'+Cs.Subject+
                    '\n'+
                    '\n Case Description:'+Cs.Description+
                    '\n'+
                    '\n Opportunity Name:'+opp.Name+
                    '\n'+
                    '\n DUE DATE:'+ Cs.Due_Date__c.format()+
                    '\n'+
                    '\n YuMe Transaction Number:'+opp.YuMe_Transaction_number__c+
                    '\n'+
                    '\n Campaign Start Date:'+Cs.Campaign_Start_Date__c.format()+
                    '\n'+
                    '\n Campaign End Date:'+Cs.Campaign_End_Date__c.format()+
                    '\n'+
                    '\n Media AP URL:'+cs.Media_Allocation_URL__c+
                    '\n'+
                    '\n Latest comment:'+Cs.RecentCaseComment__c+
                    '\n'+
                    '\n Media Notes:'+Cs.Media_Notes__c+
                    '\n'+
                    'Thanks');


                    Messaging.sendEmail(new Messaging.singleEmailMessage [] {email});
                }
            }   
        }
    }// end of if check
}// end of SendEmailtoAMsInsert method

3 Answers 3

1

This is pretty simple. Change your line 18 with below code.

Map<Id, Opportunity> opportunityMap = new Map<Id, Opportunity>([select id,Name,YuMe_Transaction_number__c from Opportunity where Id in : LstId]);

Then now remove for loop form line 23 and replace it with below code.

Opportunity opp = opportunityMap.get(cs.Opportunity__c);
if(opp == null){
    continue;
}
0
0


I would like to highlight few more points @Purushottam has already answered about using maps.

Few Optimization for your code:-
1. Use Advance For loop

List<user> Amuserid= new list<user>();
Amuserid = [select id from user where id in (select userorgroupid from groupmember where group.name='EU AMS alerts')];

Instead of this you can try like following:-

//Use Advance for loop you can remove above query
for(User u: [select id from user where id in (select userorgroupid from groupmember where group.name='EU AMS alerts')]){
    userSetIds.add(u.Id);
}

This will help you to retrieve data using Query More.

  1. Use List of List<Messaging.SingleEmailMessage>

     Messaging.sendEmail(new Messaging.singleEmailMessage [] {email});
    

    instead of sending single email from for loop.

2
  • 1
    Good points @nachiket. Just would like to add suggestion over here. Instead of Advance for loop here you can opt for query in Map constructor like below where you don't need to go for for loop. Map<Id,User> userMap = new Map<Id,User>([select id from user where id in (select userorgroupid from groupmember where group.name='EU AMS alerts')]) Commented May 25, 2017 at 7:09
  • @PurushottamBhaigade Make sense! Commented May 25, 2017 at 10:23
0

some more extra points to be considered other than what @Nachiket sir and @purushottam sir said,always in query or anywhere dont hardcode the string values use custom labels or create a separate class which contain all the string variables and use a variable which holds required value from that class in the place where it is required.for(User u: [select id from user where id in (select userorgroupid from groupmember where group.name='EU AMS alerts')]){ userSetIds.add(u.Id); }use custom label for group.name

another point is Messaging.sendEmail(new Messaging.singleEmailMessage [] {email}); this statement inside a forloop has a limitation on number of email it can send per day. if your forloop runs more than 10 times then the limit will exceed. so here is the solution for that enter image description here

if there is any better way to do this let me know and always make sure using try catch bolck.

You must log in to answer this question.

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