function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nadia GainsbourgNadia Gainsbourg 

Prevent accounts with specific record types from being deleted

Hello! How can I write a trigger to make it so accounts that have specific record types cannot be deleted? 
Thank you! 
Best Answer chosen by Nadia Gainsbourg
Steven NsubugaSteven Nsubuga
You would have to add extra statements to retrieve the additional record types, as well as an or (||) in the if statement.
See example below which checks for 3 record types. 
trigger preventAccountDeletion on Account (before delete) {

	Id recTypeId1 = Schema.SObjectType.Account.getRecordTypeInfosByName().get('RecordTypeNameA').getRecordTypeId();
	Id recTypeId2 = Schema.SObjectType.Account.getRecordTypeInfosByName().get('RecordTypeNameB').getRecordTypeId();
	Id recTypeId3 = Schema.SObjectType.Account.getRecordTypeInfosByName().get('RecordTypeNameC').getRecordTypeId();
	
    for(Account acct : trigger.old){
		if (acct.recordTypeId == recTypeId1 || acct.recordTypeId == recTypeId2 || acct.recordTypeId == recTypeId3){
			acct.addError('This Account Cannot be deleted');
		}
    }
}


 

All Answers

Steven NsubugaSteven Nsubuga
trigger preventAccountDeletion on Account (before delete) {

	Id recTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('RecordTypeName').getRecordTypeId();
    for(Account acct : trigger.old){
		if (acct.recordTypeId == recTypeId) {
			acct.addError('Account Cannot be deleted');
		}
    }

}
RecordTypeName is the name of the record type that should not be deleted.
 
Steven NsubugaSteven Nsubuga
Hi Nadia, did it work?
Nadia GainsbourgNadia Gainsbourg
Hi Steven,

It works, thank you so much! If I wanted to add a second record type, can I just separate the two by a comma? 
Steven NsubugaSteven Nsubuga
You would have to add extra statements to retrieve the additional record types, as well as an or (||) in the if statement.
See example below which checks for 3 record types. 
trigger preventAccountDeletion on Account (before delete) {

	Id recTypeId1 = Schema.SObjectType.Account.getRecordTypeInfosByName().get('RecordTypeNameA').getRecordTypeId();
	Id recTypeId2 = Schema.SObjectType.Account.getRecordTypeInfosByName().get('RecordTypeNameB').getRecordTypeId();
	Id recTypeId3 = Schema.SObjectType.Account.getRecordTypeInfosByName().get('RecordTypeNameC').getRecordTypeId();
	
    for(Account acct : trigger.old){
		if (acct.recordTypeId == recTypeId1 || acct.recordTypeId == recTypeId2 || acct.recordTypeId == recTypeId3){
			acct.addError('This Account Cannot be deleted');
		}
    }
}


 
This was selected as the best answer
Nadia GainsbourgNadia Gainsbourg
Hi Steven,

You've helped me so much, you can't even imagine! THANK YOU!!!
Steven NsubugaSteven Nsubuga
My pleasure Nadia!!