I am trying to create an Apex Class that runs on a BeforeInsert trigger and checks to see that the Task Record Type and Case Record Type are of a certain value each and if not throws an error. For example, currently a Task Record Type of Product Case Activity will save under a Case of Record Type 'Support Case'.

//Verifies that a Task Record Type must be of a certain kind in order to be 
//saved under its corresponding Case Record Type
public class CaseandTaskRecordTypes {
    public static void validateRecordType(List<Task> newList)
        Map<String,Schema.RecordTypeInfo> caseRT = 
        Map<String,Schema.RecordTypeInfo> taskRT = 
        Map<Id,List<Task>> whatIds = new Map<Id,List<Task>>();
        for ( Task t : newList ){
            if( t.WhatId!=null ){
            //Add WhatId if WhatId does not exist in map
                if( whatIds.get(t.WhatId) == null ){
                    whatIds.put(t.WhatId, new list<Task>());
            //Add all tasks associated to the WhatId
    //For tasks associated to cases, set task record type based on the case's record type
        for( Case c : [Select Id, RecordTypeId from Case where Id in : whatIds.keyset()]){
            for( Task t : whatIds.get(c.id) ){
            //Do this for new tasks being created
                if(t.RecordTypeId == taskRT.get('Product Case Activity').getRecordTypeId() && c.RecordTypeID != caseRT.get('Product Case').getRecordTypeId()){

                    t.addError('Task Record Type must align with Case Line of Business');



  • 1
    What's the challenge you are facing here? What line of code is causing the issue? Are other scenarios working as expected? More information needed to help you out.
    – SatyaV
    Jul 19, 2018 at 14:11
  • If the selected Task Record Type is "Product Case Activity" then the Task should only save if the Case Record Type is "Product Case". Currently the Task Record Type will save under any Case Record Type and does not throw an error. Jul 19, 2018 at 14:13
  • If you System.debug() next to your addError() call, can you document that execution enters that if? How are you calling this method? Is it being directly passed Trigger.new?
    – David Reed
    Jul 19, 2018 at 14:26
  • It's being called in a separate TriggerHandler apex class Jul 19, 2018 at 14:28

1 Answer 1


Updated logic of if statement to the following.

if((t.RecordTypeId != taskRT.get('Product Case Activity').getRecordTypeId()) 
(c.RecordTypeId == caseRT.get('ProductCase').getRecordTypeId()))

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .