function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kiran kumar 193Kiran kumar 193 

Asynchronous execution

HI Need help on this approach

I have a method Called

private void CreatechildRecords(List<Case> cases, Map<id,Case> oldmap) {
// Existing logic
}

when this method runnung in production we are getting 101 soql query exception.

This method is called from another method called
public void CreateCases(list<Case> newList, list<Case> oldList,map<Id,Case> oldMap)
{
   CreatechildRecords(newlist, oldMap);
}

and this method is calling from trigger by passing context variables. Now My requirement is I want to execute child cases method to be asyncronous. PLease suggest how do I modify the code to support @future annotation.

Please help
Amit Chaudhary 8Amit Chaudhary 8
There are other solution as well to fix 101 SOQL error.
1) https://help.salesforce.com/apex/HTViewSolution?id=000181404&language=en_US
2) https://help.salesforce.com/apex/HTViewSolution?id=000213152&language=en_US



Here are some best practices that will stop the error messages and/or help you avoid hitting the Governors Limit:
1. Since Apex runs on a Multitenant structure, Apex runtime engine strictly enforces limits to ensure code doesn't monopolize shared resources. Learn about the Governors Limit.
2. Avoid SOQL queries that are inside FOR loop. 
3. Check out the Salesforce Developer Blog where you can find Best Practices for Triggers.
4. Review best practices for Trigger and Bulk requests on our Force.com Apex Code Developer's Guide. 
5. Be sure you're following the key coding principals for Apex Code in our Developer's Guide.


Let us know if this will help you

Thanks
Amit Chaudhary
sandeep@Salesforcesandeep@Salesforce
Hi Kiran, 

All you need to do is 
1. Please stop cyclic execution. Here trigger written on case is caling it self because while creation of case in same execution you are creating child records. 
Approach: keep a static variable of any any class and switch its value just after your one execution.

2. If you really want to keep chid record insertion in asynchronous way then you just need to apply @future annotation on method of CreatechildRecords
Here you get an idea how to use future method 
https://developer.salesforce.com/blogs/developer-relations/2013/06/passing-objects-to-future-annotated-methods.html

Thanks
Sandeep Singhal
http://www.codespokes.com/
 
Kiran kumar 193Kiran kumar 193
Hi Sandeep,

Thanks for your reply....
Here is my Create Child cases code... I tried put Static variable and @ future annotation. This is the method which is calling from class along with other methods.
public without sharing class NHWCaseTriggerHandler {

public void afterUpdate(list<Case> newList, list<Case> oldList,map<Id,Case> oldMap) {
        List<Case> newParentCaseList = new List<Case>();
        Map<Id,Case> oldParentCaseMap = new Map<Id,Case>();
        List<Case> casesToBeSendMobileSurvey = new list<Case>();
        List<Case> casesToBeSentInternalMobileEmail = new List<Case>();
        Map<Id,String> caseToSFEmailStatus = new Map<Id,String>();
        Map<Id,Case> newCaseMap = new Map<Id,Case>();
        if(!isChildCasesExecuted){
            createChildCases(newlist, oldMap);
        }

        if(!isExecuted){
            isExecuted=true;
            syncWithPeopleforce(newlist, oldList);
            closeParentCase(newList, oldList);
            //createNonHardwareChildCases(newList, oldMap);
            childcasesWithEmployeeIds(newList,oldMap);
        }

        if(!isChildCaseUpdateExecuted){
            isChildCaseUpdateExecuted = true;
        
        List<Case> newListWithChildCases = new List<Case>([select ParentId,RecordTypeId,StartDate__c,Reporting_Manager__c,Reporting_Manager_Email__c,Cost_Center__c,Business_Unit__c,Origin,(select StartDate__c,Reporting_Manager__c,Reporting_Manager_Email__c,Cost_Center__c,Business_Unit__c,Origin from Cases) from Case where Id in :newList and ParentId = null]);
        for(Case c : newListWithChildCases){
            if(c.ParentId == null && c.RecordTypeId == caseRecordTypeMap.get('New Hire Process - Onboarding').getRecordTypeId()){
                newParentCaseList.add(c);
                oldParentCaseMap.put(c.Id,oldMap.get(c.Id));
            }
        }
        if(newParentCaseList.size() > 0){
            updateChildCaseCaseStartDate(newParentCaseList,oldParentCaseMap);
            updateChildCaseCaseHiringManager(newParentCaseList,oldParentCaseMap);
            updateChildCaseCaseHiringManagerEmail(newParentCaseList,oldParentCaseMap);
            updateChildCaseCaseCostCenter(newParentCaseList,oldParentCaseMap);
            updateChildCaseCaseBusinessUnit(newParentCaseList,oldParentCaseMap);
        }
        if(childCasesToUpdate.size() >0){
            update childCasesToUpdate.Values();
        }
        }

        for(Case c:newList){
            if(!isMobilePhoneEmailSent && c.Origin == 'NHW' && c.Mobile_Phone_Required__c == 'Yes' && date.today().daysBetween(c.StartDate__c) > 0 && c.ParentId == null && c.Status == 'Sent to Supportforce' && c.RecordTypeId == caseRecordTypeMap.get(
               'New Hire Process - Onboarding').getRecordTypeId() &&
                c.Office_Country__c != null && !(c.Office_Country__c.startsWith('United States') || c.Office_Country__c == 'US' || c.Office_Country__c == 'USA' || c.Office_Country__c == 'Canada' || c.Office_Country__c == 'CA')){
                if(oldMap.get(c.Id).ParentId != null || oldMap.get(c.Id).Status != 'Sent to Supportforce' || oldMap.get(c.Id).RecordTypeId != caseRecordTypeMap.get(
                   'New Hire Process - Onboarding').getRecordTypeId() || oldMap.get(c.Id).Origin != 'NHW' || oldMap.get(c.Id).Mobile_Phone_Required__c != 'Yes' || date.today().daysBetween(oldMap.get(c.Id).StartDate__c) <= 0
                || (oldMap.get(c.Id).Office_Country__c.startsWith('United States') || oldMap.get(c.Id).Office_Country__c == 'US' || oldMap.get(c.Id).Office_Country__c == 'USA' 
                    || oldMap.get(c.Id).Office_Country__c == 'Canada' || oldMap.get(c.Id).Office_Country__c == 'CA')){
                    newCaseMap.put(c.Id,c); 
                    isMobilePhoneEmailSent = true;
                }   
            }
        }
        if(newCaseMap != null && newCaseMap.size() > 0){
            for(Case c: [select Id,New_Hire_Supportforce_contact__r.Status__c from Case where Id in:newCaseMap.keySet()]){
                caseToSFEmailStatus.put(c.Id,c.New_Hire_Supportforce_contact__r.Status__c);
            }
        }

        for(Case c: newCaseMap.values()){
            if(caseToSFEmailStatus.get(c.Id) == 'Active'){
                casesToBeSentInternalMobileEmail.add(c);
            }
        }    
        if(casesToBeSentInternalMobileEmail != null && casesToBeSentInternalMobileEmail.size() > 0){
            sendInternalMobileEmail(casesToBeSentInternalMobileEmail);
        }   
    }
 
  
Kiran kumar 193Kiran kumar 193
private void createChildCases(list<Case> newList, Map<Id,Case> oldMap) {
        list<Case> casesToAdd = new list<Case>();
        Map<String,Case> casesToAddMap = new Map<String,Case>();
        Case tempCase, tempCase1, tempCase2;
        Map<Id, String> caseIdToCCMap = new Map<Id, String>();
        Map<Id, String> caseIdToBUMap = new Map<Id, String>();
        Map<Id,String> ccComboMap = getCostCentersCombo();
        Map<Id,String> buComboMap = getBusinessUnitCombo();
        Map<Id,String> caseToSFEmailStatus = new Map<Id,String>();
        Map<Id,Case> newCaseMap = new Map<Id,Case>();
        NH_Settings__c settings =NH_Settings__c.getInstance();
        for(Case c:newList){
            if (!c.Existing_Equipment__c && c.Mobile_Phone_Required__c == 'Yes' &&
                (c.Office_Country__c.startsWith('United States') || c.Office_Country__c == 'US' || c.Office_Country__c == 'USA' || c.Office_Country__c == 'Canada' || c.Office_Country__c == 'CA') &&
                 date.today().daysBetween(c.StartDate__c) > 0 && c.New_Hire_Supportforce_contact__c != null){
                    newCaseMap.put(c.Id,c);
            }
        }
        if(newCaseMap != null && newCaseMap.size() > 0){
            for(Case c: [select Id,New_Hire_Supportforce_contact__r.Status__c from Case where Id in:newCaseMap.keySet()]){
                caseToSFEmailStatus.put(c.Id,c.New_Hire_Supportforce_contact__r.Status__c);
            }    
        }
       
        Database.DMLOptions dmlOpts = new Database.DMLOptions();
        dmlOpts.assignmentRuleHeader.assignmentRuleId = caseARId; 

        //Get all the child cases
        Map<String, Map<String, Case>> childCasesMap = new Map<String, Map<String, Case>>();
        for (Case c : [SELECT Id,NH_Is_Exact_Target__c,Business_Unit__c,Cost_Center__c, (SELECT Id, Subject, ParentId, Purchasing_Approved__c FROM Cases) FROM Case WHERE Id IN :newList AND Origin='NHW']) {
            if (c.Cases != null && !c.Cases.isEmpty()) {
                Map<String, Case> childCases = new Map<String, Case>();
                for (Case cc : c.Cases) {
                    childCases.put(cc.Subject, cc);
                }
                childCasesMap.put(c.Id, childCases);
            }
            if(c.NH_Is_Exact_Target__c && c.Business_Unit__c!= null && c.Cost_Center__c != null){
                String cc = c.Cost_Center__c.split('-',0)[0];
                String bu = c.Business_Unit__c.split('-',0)[0];
                caseIdToCCMap.put(c.id,cc);
                caseIdToBUMap.put(c.id,bu);
            }
        }
        
        //Iterate through new/updated cases
        for (Case c : newList) {
            if (c.RecordTypeId == caseRecordTypeMap.get('New Hire Process - Onboarding').getRecordTypeId()
                    && c.Internal_Support_Category__c != null
                    && c.Internal_Support_Category__c.contains('New Hire Onboarding Request')) {
                String hardwareReqSubject = 'New Hire Hardware Request for: ' + 
                        c.New_Hire_First_Name__c + ' ' + c.New_Hire_Last_Name__c;
                String extMobilityCiscoCaseSubject = 'New Hire User Access Request for: ' + c.New_Hire_First_Name__c + ' ' + c.New_Hire_Last_Name__c +
                        ' - Phone and Voicemail - Cisco'; 
                        
                String extMobilityI3CaseSubject = 'New Hire User Access Request for: ' + c.New_Hire_First_Name__c + ' ' + c.New_Hire_Last_Name__c +
                        ' - Phone and Voicemail - i3';      

                String mobilePhoneCaseSubject = 'New Hire Mobile Request for: ' +  c.New_Hire_First_Name__c + ' ' + c.New_Hire_Last_Name__c;                  
                Map<String, Case> existingChildCases = childCasesMap.get(c.Id);

                if(c.Purchasing_Approved__c && c.NH_VPN_Access_Required__c){
                    Case vpnChildCase = createVPNAccessCase(c, existingChildCases, dmlOpts); 
                    if(vpnChildCase!=null){
                        casesToAdd.add(vpnChildCase);
                    }
                }
                if (c.NHW_Access_Code__c != null && c.Purchasing_Approved__c == true) {
                    casesToAdd.addAll(parseAccess(c, existingChildCases, dmlOpts));
                }
                if (c.Purchasing_Approved__c && existingChildCases != null && existingChildCases.containsKey(hardwareReqSubject)
                        && existingChildCases.get(hardwareReqSubject).Purchasing_Approved__c != true) {
                    Case hardwareReqCase = existingChildCases.get(hardwareReqSubject);
                    hardwareReqCase.Purchasing_Approved__c = true;
                    casesToAdd.add(hardwareReqCase);
                }
                if (!c.Existing_Equipment__c && (existingChildCases == null || !existingChildCases.containsKey(hardwareReqSubject))
                    && ((c.ComputerType__c != null && c.ComputerType__c != 'Not Required') || (c.Laptop_Type__c != null && c.Laptop_Type__c != ''))) {
                    tempCase = c.clone();
                    tempCase.RecordTypeId = c.Employment_Type__c == 'Regular Employee' ? 
                    caseRecordTypeMap.get('New Hire Process').getRecordTypeId() : 
                        caseRecordTypeMap.get('Contractor New Hire Process').getRecordTypeId();
                    tempCase.ParentId = c.Id;
                    tempCase.Internal_Support_Category__c = 
                            'IT Helpdesk: Hardware: New Hire Equipment Request';
                    tempCase.Subject = 'New Hire Hardware Request for: ' + c.New_Hire_First_Name__c + 
                            ' ' + c.New_Hire_Last_Name__c;
                    tempCase.Ship_to_Contact__c = c.New_Hire_First_Name__c + ' ' 
                            + c.New_Hire_Last_Name__c;
                    tempCase.Status = 'New';
                    tempCase.Origin = 'NHW';
                    tempCase.Type = 'Other'; 
                    tempCase.Priority = '3 - Low';
                    if(c.NH_Is_Exact_Target__c && caseIdToBUMap.get(c.id) != null && caseIdToCCMap.get(c.id) != null){
                        for(Id i:buComboMap.keySet()){
                            if(caseIdToBUMap.get(c.id) == buComboMap.get(i) && caseIdToCCMap.get(c.id) == ccComboMap.get(i)){
                                tempCase.Description = 'MARKETING CLOUD IMAGE REQUIRED\n\n' + tempCase.Description;    
                            }
                        }
                    }
                    String cCenter = c.Cost_Center__c.split('-',0)[0];
                    String bUnit = c.Business_Unit__c.split('-',0)[0];
                    
                    if(bUnit.contains(settings.NewHire_BU__c) && cCenter.contains(settings.NewHire_CostCenter__c))
                    {
                        if(tempCase.Description!=null)
                        {
                        tempCase.Description=tempCase.Description+'\r\n'+'\r\n'+settings.Description__c;
                        }
                        else
                        {
                           tempCase.Description=settings.Description__c;
                        }
                    }
                    tempCase.setOptions(dmlOpts);
                    casesToAdd.add(tempCase);
                }
                if (!c.Existing_Equipment__c && c.Mobile_Phone_Required__c == 'Yes' && (existingChildCases == null || !existingChildCases.containsKey(mobilePhoneCaseSubject)) &&
                    (c.Office_Country__c.startsWith('United States') || c.Office_Country__c == 'US' || c.Office_Country__c == 'USA' || c.Office_Country__c == 'Canada' || c.Office_Country__c == 'CA') &&
                     date.today().daysBetween(c.StartDate__c) > 0 && c.New_Hire_Supportforce_contact__c != null && 
                     caseToSFEmailStatus != null && caseToSFEmailStatus.get(c.Id) != null && caseToSFEmailStatus.get(c.Id) == 'Active') {
                    tempCase = c.clone();
                    tempCase.RecordTypeId = caseRecordTypeMap.get('Mobile Request Record Type').getRecordTypeId();
                    tempCase.ParentId = c.Id;
                    tempCase.Subject = mobilePhoneCaseSubject;
                    tempCase.Ship_to_Contact__c = c.New_Hire_First_Name__c + ' ' + c.New_Hire_Last_Name__c;
                    tempCase.Status = 'Information Not provided';
                    tempCase.Approval__c = 'Approved';
                    tempCase.Internal_Support_Category__c = '';
                    tempCase.Origin = 'NHW';
                    tempCase.Type = 'Other'; 
                    tempCase.Priority = '3 - Low';
                    tempCase.Location__c = c.Office_Country__c;
                    tempCase.Approval_Date__c = c.LastModifiedDate;
                    tempCase.ContactId = c.New_Hire_Supportforce_contact__c;
                    tempCase.setOptions(dmlOpts);
                    casesToAdd.add(tempCase);
                }
                for(NHW_AccessCode accessC : (List<NHW_AccessCode>) JSON.deserialize(c.NHW_Access_Code__c,List<NHW_AccessCode>.class)){
                    if(accessC.accessType == 'Mobile'){
                            for(NHW_AccessDetails accessD: accessC.accessDetailList){
                                if (!c.Existing_Equipment__c && (existingChildCases == null || !existingChildCases.containsKey(extMobilityCiscoCaseSubject)) && accessD.Name.contains('Cisco')){
                                        tempCase1 = c.clone();
                                        tempCase1.Subject = extMobilityCiscoCaseSubject;
                                        tempCase1.RecordTypeId = c.Employment_Type__c == 'Regular Employee' ? 
                                        caseRecordTypeMap.get('New Hire Process').getRecordTypeId() : 
                                            caseRecordTypeMap.get('Contractor New Hire Process').getRecordTypeId();
                                        tempCase1.ParentId = c.Id;
                                        tempCase1.Internal_Support_Category__c = 
                                                'IT Helpdesk: Phone: Extension Mobility';
                                        tempCase1.Ship_to_Contact__c = c.New_Hire_First_Name__c + ' ' 
                                                + c.New_Hire_Last_Name__c;
                                        tempCase1.Status = 'New';
                                        tempCase1.Origin = 'NHW';
                                        tempCase1.Type = 'Other'; 
                                        tempCase1.Priority = '3 - Low';
                                        tempCase1.setOptions(dmlOpts);
                                        casesToAdd.add(tempCase1);
                                        //casesToAddMap.put(extMobilityCiscoCaseSubject,tempCase1);
                                }        
                                if (!c.Existing_Equipment__c && (existingChildCases == null || !existingChildCases.containsKey(extMobilityI3CaseSubject)) && accessD.Name.contains('i3')) {    
                                        tempCase2 = c.clone();
                                        tempCase2.Subject = extMobilityI3CaseSubject;
                                        tempCase2.RecordTypeId = c.Employment_Type__c == 'Regular Employee' ? 
                                        caseRecordTypeMap.get('New Hire Process').getRecordTypeId() : 
                                            caseRecordTypeMap.get('Contractor New Hire Process').getRecordTypeId();
                                        tempCase2.ParentId = c.Id;
                                        tempCase2.Internal_Support_Category__c = 
                                                'IT Helpdesk: Phone: Extension Mobility';
                                        tempCase2.Ship_to_Contact__c = c.New_Hire_First_Name__c + ' ' 
                                                + c.New_Hire_Last_Name__c;
                                        tempCase2.Status = 'New';
                                        tempCase2.Origin = 'NHW';
                                        tempCase2.Type = 'Other'; 
                                        tempCase2.Priority = '3 - Low';
                                        tempCase2.setOptions(dmlOpts);
                                        casesToAdd.add(tempCase2);
                                        //casesToAddMap.put(extMobilityI3CaseSubject,tempCase2);
                                        
                                }
                            }
                    }
                }            
                if (c.NH_Is_People_Manager__c && c.Purchasing_Approved__c) {
                    String talentforceSubject = 'New Hire Manager Request for Talentforce: ' + 
                            c.New_Hire_First_Name__c + ' ' + c.New_Hire_Last_Name__c;
                    if (existingChildCases == null || !existingChildCases.containsKey(talentforceSubject)) {
                        tempCase = c.clone();
                        tempCase.RecordTypeId = c.Employment_Type__c == 'Regular Employee' ? 
                                caseRecordTypeMap.get('New Hire Process').getRecordTypeId() : 
                                    caseRecordTypeMap.get('Contractor New Hire Process').getRecordTypeId();
                                tempCase.ParentId = c.Id;
                                tempCase.Internal_Support_Category__c = 
                                        'Internal Talentforce.com App: User Access';
                                tempCase.Subject = 'New Hire Manager Request for Talentforce: ' + 
                                        c.New_Hire_First_Name__c + ' ' + c.New_Hire_Last_Name__c;
                                tempCase.Ship_to_Contact__c = c.New_Hire_First_Name__c + ' ' 
                                        + c.New_Hire_Last_Name__c;
                                tempCase.Status = 'New';
                                tempCase.Origin = 'NHW';
                                tempCase.Type = 'Other'; 
                                tempCase.Priority = '3 - Low';
                                tempCase.setOptions(dmlOpts);
                                casesToAdd.add(tempCase);
                    }
                }
            }    
        }
        
        if(!casesToAdd.isEmpty()){
            isChildCasesExecuted = true;
            upsert casesToAdd;
        }



    }

 
Kiran kumar 193Kiran kumar 193
Hi Sandeep,
Can you Please help me on the above code... and Afterupdate method calling from Trigger