1

I have seen many posts with the same title but none of the provided answers explains why does this error occur.

EDIT: My goal is to add another value to an existing case. I want to populate this case field: User_Agent__c with the a value from the LiveChatTranscript record. The existing case has already data stored in it and of course I don't want to override it.

 Trigger Chat_copyUserAgentToNewCase on LiveChatTranscript(before insert) {
     List < Case > lstcases = new List < Case > ();
     for (LiveChatTranscript trans: Trigger.new) {
         if (trans.UserAgent != null) {
             Case c = new Case(Id = trans.CaseId, User_Agent__c = trans.UserAgent);
             lstcases.add(c);
         }
     }
     if (!lstcases.isEmpty()) {
         update lstcases; // on this row I get the error
     }

 }
  • in case if you create new case, you need to insert that, not update – kurunve Jun 26 '17 at 7:05
  • Do you need to insert a new case or update en existing case? This is really not clear. – Martin Lezer Jun 26 '17 at 7:09
  • I am updating an existing case, I want to populate the field User_Agent__c on the existing case with trans.UserAgent – Json Jun 26 '17 at 7:27
2

This code changes will stop the error (by ignoring records that don't have a Case Id):

     Map<Id, Case> cases = new Map<Id, Case>();
     if (trans.CaseId != null && trans.UserAgent != null) {
         Case c = new Case(Id = trans.CaseId, User_Agent__c = trans.UserAgent);
         cases.put(c.Id, c);
     }
     update cases.values();

Using a Map ensures there will never be two records of the same Id in the update (which would throw an error).

| improve this answer | |
  • Thanks @Keith C, quick question: is it not recommended to check if the list/map is not empty before executing DML operation? – Json Jun 26 '17 at 9:41
  • @Dante Originally DML on empty lists did count against limits but that was addressed many API versions ago so no need to check. – Keith C Jun 26 '17 at 9:44

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.