You need to sign in to do that
Don't have an account?
Chris Husted
Help with Apex Trigger for Contacts
Hello -
I have a new trigger in place to prevent users from deleting of contacts from our environment.
Here is a copy of my code:
trigger DeletePrevention on Contact (before delete) {
for (Contact mo : Trigger.old) {
mo.addError('Youre Not Allowed to Delete Client Contacts');
}
}
However, I need to figure out to restrict this to ONLY one RecordType of Contact ('Client').
Any suggestions or help would be greatly appreciated.
Thanks!
I have a new trigger in place to prevent users from deleting of contacts from our environment.
Here is a copy of my code:
trigger DeletePrevention on Contact (before delete) {
for (Contact mo : Trigger.old) {
mo.addError('Youre Not Allowed to Delete Client Contacts');
}
}
However, I need to figure out to restrict this to ONLY one RecordType of Contact ('Client').
Any suggestions or help would be greatly appreciated.
Thanks!
Please try following code.
trigger DeletePrevention on Contact (before delete) {
//Retrive Client Record Type Id
public Id clientRecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Client').getRecordTypeId();
for (Contact mo : Trigger.old) {
if(mo.recordTypeId != null && (clientRecordTypeId !=null && clientRecordTypeId == mo.recordTypeId))
{
mo.addError('Youre Not Allowed to Delete Client Contacts');
}
}
}
Best Regards,
-Vivek
Vivek.deshmane@gmail.com
All Answers
Please try following code.
trigger DeletePrevention on Contact (before delete) {
//Retrive Client Record Type Id
public Id clientRecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Client').getRecordTypeId();
for (Contact mo : Trigger.old) {
if(mo.recordTypeId != null && (clientRecordTypeId !=null && clientRecordTypeId == mo.recordTypeId))
{
mo.addError('Youre Not Allowed to Delete Client Contacts');
}
}
}
Best Regards,
-Vivek
Vivek.deshmane@gmail.com
Please let us know if this will help you.
Thanks,
Amit Chaudhary
However, I'm running into an issue with my Apex class (test coverage) needed to deploy the trigger to production.
If possible, can you help?
Please try below code.Hope this will help in test coverage
@isTest
private class NoDeleteonContactTest
{
private static testmethod void NoDeleteonClientContactTest()
{
Test.startTest();
try{
Id clientRecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Client').getRecordTypeId();
Account Acct = new Account(Name = 'Test');
insert Acct;
contact cont = new contact(Accountid = Acct.id, LastName='Test',RecordTypeId=clientRecordTypeId);
insert cont;
delete cont;
}catch (Exception e) {
System.assert(e.getMessage().contains('Youre Not Allowed to Delete Client Contacts'));
}
Test.stopTest();
}
}
Please let me know if this help you and mark the best answer
Best Regards,
-Vivek
vivek.deshmane@gmail.com