0

I'm trying to update OwnerId on the a List<Case> once the fields are updated on a case object, only first case is getting updated but not all cases. I need to update all cases with same OwnerId.

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);
    }

    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;
    }   
}
  • 1
    There's a big logic problem with your code. You're looping through the list of users and then looping through all the cases. So all the cases will have the last user found as owner. Please explain more precisely your use case. – Martin Lezer Mar 1 '17 at 13:41
  • 1
    @patha - As mentioned by Martin, please explain your requirement.And your are missing } in your code.Add it in the last line – Samir Mar 1 '17 at 13:45
3

As as said in my comment, the problem is that you are assigning all the cases found to the last user of your for loop.

Also, you're not calling an update on the cases list.

This should work:

trigger caseAssignment on Case (after insert, after update) {
    Map<Id, Id> ownerIdByAccountId = new Map<Id, Id>();
    Set<Id> currentCasesIds = new Set<Id>();
    for(Case caseobj : trigger.new){
        Boolean caseObjChanged = Trigger.isUpdate && (Trigger.oldMap.get(caseobj.Id).AccountId != caseobj.AccountId || Trigger.oldMap.get(caseobj.Id).OwnerId != caseobj.OwnerId);

        if(Trigger.isInsert || caseObjChanged){
            ownerIdByAccountId.put(caseObj.AccountId, caseObjOwnerId);
            currentCasesIds.add(caseobj.Id);
        }
    }

    List<Case> casesToUpdate = new List<Case();
    for(Case cas : [Select Id, OwnerId, AccountId From Case where AccountId IN: ownerIdByAccountId.keySet() AND Id NOT IN :currentCasesIds]){       
        Id newOwnerId = ownerIdByAccountId.get(cas.AccountId);
        if(cas.OwnerId != newOwnerId){
            cas.OwnerId = newOwnerId;

            casesToUpdate.add(cas);
        }
    }

    update casesToUpdate;
}

The first loop is adding only the cases with the accountid changed or the new cases.

Thanks to a Map, you are able to link the cases account id to an owner id to assign it right later.

Finally, we call an update on the cases that changed.

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.