Apex Trigger- how to update all case owners using trigger?

2k Views Asked by At

when user clicks on case to change caseOwner/user, i have to add this user to all associated cases(per customer). I am using below code ,but it is updating only one record/case. i can see in debug logs all cases were updated with latest owner but not really updated/stored in caseObject. please help me this.

    trigger caseAssignment on Case (after insert, after update) {

      set<id> ownerId = new Set<Id>();
      set<id> customerId = new set<Id>();
    for(Case caseobj : trigger.new){

            ownerId.add(caseobj.OwnerId); 
            customerId.add(caseobj.AccountId);
    }


for( User user:[Select id, FirstName, LastName from user where Id IN  :ownerId]){   

    for(Case cas : [Select Id, OwnerId, First_Name__c, CaseNumber, AccountId From Case where AccountId IN: customerId]){        

        cas.OwnerId = user.Id;

    }  


}
2

There are 2 best solutions below

0
On

Without an update DML statement, your code will have no effect on your data.

Probably should create an update list

i.e. list updateCaseList = new list()

Then in your inner for loop, add "cas" to updateCaseList and then at the end of the method, issue the update command (update updateCaseList).

0
On

Assuming that the logic you wrote is correct you're never updating the cases

trigger caseAssignment on Case (after insert, after update) 
{

    Set<Id> ownerId = new Set<Id>();
    Set<Id> customerId = new Set<Id>();
    List<Case> casesToUpdate = new List<Case>();

    for(Case caseobj : trigger.new)
    {
        ownerId.add(caseobj.OwnerId); 
        customerId.add(caseobj.AccountId);
    }


    for( User user:[Select id, FirstName, LastName from user where Id IN  :ownerId])
    {   
        for(Case cas : [Select Id, OwnerId, First_Name__c, CaseNumber, AccountId From Case where AccountId IN: customerId])
        {        
            Case c = new Case();
            c.ID = cas.ID;
            c.OwnerId = user.Id;
            casesToUpdate.add(c);
        }  
    }

    update casesToUpdate;
}