Apex Trigger for restricting duplicate Cases (with the same subject) #inSalesforce

Apex Trigger for restricting duplicate Cases (with the same subject):


trigger CaseTrigger on Case (before insert, before update) {
    Map<String, Case> cMap = new Map<String, Case>();
    for (Case c : System.Trigger.new) {
        if (System.Trigger.isInsert || (c.Subject != System.Trigger.oldMap.get(c.Id).Subject)) {
            if (cMap.containsKey(c.Subject)) {
                c.Subject.addError('May be duplicate! A Case already exists with this Subject.');
            } else {
                cMap.put(c.Subject, c);
            }
        }
    }
    for (Case c : [SELECT Subject FROM Case WHERE Subject IN :cMap.KeySet()]) {
        Case newCase = cMap.get(c.Subject);
        newCase.Subject.addError('May be duplicate! A Case already exists with this Subject.');
    }
}


Test Class for the above trigger:


@isTest
private class TestCaseTriggers {
    static testMethod void CaseTriggerUnitTest() {
        Case c = new Case();
        c.Subject = 'Sample';
        c.Priority = 'Low';
        c.Status = 'New';
        c.Origin = 'Email';
        insert c;
        Case cs = new Case();
        cs.Subject = 'Sample';
        cs.Priority = 'High';
        cs.Status = 'In Progress';
        cs.Origin = 'Phone';
        try{
            insert cs;
        }
        catch(System.DMLException e){
            System.assert(e.getMessage().contains('May be duplicate! A Case already exists with this Subject.'));
        }
    }
}






Comments