0

I am new to Salesforce development. I want to write one batch apex which will look into user object and see if manger field is getting updated for User record, then it will update user manager for all the cases that are owned by the user(having record type : Support, Support_New and Status!=Close) for which we have updated manger and update case record with updated user manager name in a new custom lookup field Case_Owner_Manager__c. Also if user's manager is changed at User object level, then it should be updated on Case_Owner_Manager__c in Case record.

Here is the Batch class I have written:

global class DemoManagerUpdateClass implements Database.Batchable<sObject> 
{
   global Database.Querylocator start(Database.BatchableContext BC)
   {
       return Database.getQueryLocator([Select Id,CaseNumber,Status,RecordTypeId,OwnerId,Owner.Name,Owner.Type FROM Case where Status!='Closed'AND Owner.Type='User']);
   }
    
   global void execute(Database.BatchableContext BC,List<Case> scope)
    {
        
        Set<Id> caseIds = new Set<Id>();
        
        for(Case caseid : scope)
        {
            caseIds.add(caseid.id);
        }
        List<RecordType> rTypes = [Select id, Name From RecordType Where sObjectType = 'Case'];
        Map<ID, String> maprtID_rtName = new Map<ID, String>();
        for(RecordType rTypeObj : rTypes)
        {
            maprtID_rtName.put(rTypeObj.id, rTypeObj.Name);
        }   
        List<Case> caseRec = [SELECT Id,CaseNumber,Status,RecordTypeId,OwnerId,Owner.Name,Owner.Type FROM Case];
        for(Case c:caseRec)
        {
            if( c.Owner.Type=='User' && c.Status!='Closed')
            {
                String rType;
                if(maprtID_rtName.containsKey(c.RecordTypeId))
                {
                    rType  =   maprtID_rtName.get(c.RecordTypeId);                   
                    if(rType == 'Support' || rType == 'Support_New' )
                    {    
                         List<User> usersWithManagers = [Select Id, Manager.FirstName, Manager.LastName, Manager.email, ManagerId from user WHERE Id IN : caseIds];
                         List<Case> updateCaseManager = new List<Case>();
                         Map<Id, User> userMapManager = new Map<Id, User>();
                         for(User userRec : usersWithManagers)
                         {
                            userMapManager.put(userRec.Id, userRec);
                    
                         } 
                     
                         if(!userMapManager.isEmpty())
                          {
                            //Query All cases whose Owner id in the MAP and for Recordtype's Support and Support_New.
                            for(Case cs :[Select Id, ownerId,  Case_Owner_Manager__c  from Case where (ownerId IN :userMapManager.Keyset())])
                            {
                                 if(userMapManager.get(cs.ownerId)!= null)
                                 {
                                    if(userMapManager.get(cs.ownerId).manager.firstname <> null && userMapManager.get(cs.ownerId).manager.lastname <> null)
                                    {
                                        cs.Case_Owner_Manager__c = userMapManager.get(c.ownerId).manager.firstname + ' ' +userMapManager.get(c.ownerId).manager.lastname;
                                    }
                                    else
                                    {
                                        cs.Case_Owner_Manager__c = '';
                                    }
                                     
                                   updateCaseManager.add(cs);  
                                    
                                }    
                            }
                              
                           database.update(updateCaseManager);
                          }
                        system.debug('------- After update Case Call-----------'); 
                    }
                }
            }
        }
    }
   global void finish(Database.BatchableContext BC){}                   
       
}

Currently, this class is not updating Case_Owner_Manager__c on Case object as expected. Can anyone please help.

1

You're returning a query from the Case object, then trying to assign the values to a User object. This causes the execute method to be skipped. You need to change your query to use the User object.

global Database.Querylocator start(Database.BatchableContext BC) {   
    return Database.getQueryLocator([Select Id FROM User]);
}

Your code also has a couple of other problems. You're using queries inside a loop (which will break governor limits), and you have inconsistent brace usage, which makes the code slightly harder to read.

Also, finally:

if(updateCaseManager.size()>0){
    database.update(updateCaseManager);
} 

It's not necessary to check if a list is empty before you do a DML. This is an old carry-over from many years ago that is no longer necessary.


Reviewing your code, I optimized it to just:

global class DemoManagerUpdateClass implements Database.Batchable<sObject> {
    global Database.Querylocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([Select OwnerId FROM Case WHERE Status != 'Closed'AND Owner.Type='User' AND RecordType.DeveloperName IN ('Suppport','Support_New')]);
    }
    global void execute(Database.BatchableContext BC,List<Case> scope) {
        List<Case> caseRec = [Select OwnerId FROM Case WHERE Status != 'Closed'AND Owner.Type='User' AND RecordType.DeveloperName IN ('Suppport','Support_New') AND Id = :scope];
        Map<Id, User> users = new Map<Id, User>();
        for(Case record: caseRec) {
            users.put(caseRec.OwnerId, null);
        }
        users.putAll([SELECT Manager.FullName FROM User WHERE Id = :users.keySet()]);
        for(Case c:caseRec) {
            cs.Case_Owner_Manager__c = users.get(c.OwnerId)?.Manager.FullName;
        }
        update caseRec;
    }
    global void finish(Database.BatchableContext BC){}
}
2
  • thanks for looking into the code. I have updated the batch. Can you please check what is wrong here and help me with the correct code.
    – Avi_SFDC
    Jul 30 at 11:29
  • @AvaniPaliwal I optimized your new code. It turns out you've got a lot of unnecessary code in there.
    – sfdcfox
    Jul 30 at 14:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.