Monday, October 3, 2011

Trigger to Prevent Deleting a Record based on Record Type

Fresh off of a full week of Development Classes in Washington D.C. it was time to put that knowledge to work! Here's the scenario:

We need to prevent a user from deleting a contact when they are a particular record type. I put this together in my developer account so it is a rather contrived example but it can be altered to fit the needs of anyone...

Trigger:

/*
If a user attempts to delete under these conditions,
prevent the delete and display this message at the top of the Contact page layout:
“You are not permitted to delete a Contact with a recrod type of 'Other'.”.
*/

trigger TestContactBeforeDeleteTrigger on Contact (before delete) {


List<RecordType> recType = [select id from RecordType where name = 'Record Type A' AND sobjecttype = 'Contact' AND IsActive = TRUE limit 1];

 if(!recType.isempty()){
String RecordTypeAid = rectype[0].id;

  for(Contact con: trigger.old){

       if(con.RecordTypeId == RecordTypeAid){
         con.addError('You are not permitted to delete an account with a record type of "Other"');
             }
        }
}
}


Test Class:

/*
Test class for TestContactBeforeDeleteTrigger
*/

@isTest
private class TestBeforeDelete {

    static testMethod void myUnitTest() {
     
List<RecordType> recType = [select id from RecordType where name = 'Record Type A' AND sobjecttype = 'Contact' AND IsActive = TRUE limit 1];

  if(!recType.isempty()){
String RecordTypeAid = rectype[0].id;
   
Contact c1 = new ContCt();
c1.LastName = 'Test Last Name for Trigger';
c1.RecordTypeID = RecordTypeAid;

        insert c1;
   
        try{
         delete c1;
        }
        catch (dmlexception e){
       
         system.assert(e.getMessage().contains('You are not permitted to delete an account with a record type of "Other"'),
         e.getMessage() );
      }
    }
    }
}

A special thanks to Peter Gruhl who taught the DEV501 class. The class was quite a bit to handle and he taught it VERY well. Thanks Peter!

This code was updated on 6/26/2013 to remove any references to hard coded Record Type IDs. I have included a SOQL line that pulls the RecordTypeID from the system dynamically so this will work from Sandbox to Production where the record type ids are different.

4 comments:

  1. Hi,
    I'm trying to apply this code to my own app and I'm getting some errors.
    Is this exact code tested?

    ReplyDelete
  2. my bad, i didn't copy it right

    ReplyDelete
  3. Thank you for your note Gil. I have taken a look at this code and actually modified it to make it more dynamic by removing any hard coded RecordTypeID's. The previous version of this code would work in Sandbox, but when you would move it to production it may not work properly due to the fact that the RecordTypeID is typically different from Sandbox to Production.

    ReplyDelete