Skip to main content The Trailblazer Community will be unavailable from 2/1/2025 to 2/2/2025. Please plan your activities accordingly.
Hello,

Below is a code I created for validating contact deletion. But it dosent seem to work, I'm able to delete the contacts from accounts whose country is India. The trigger is active. Can someone please let me know the reason ?

1    trigger SV1 on Contact (before delete) {

2        //donot allow deletion of any contact whose account country is India

3        for (Contact cont : trigger.old){

4                    if(cont.Account.country__c == 'India'){

5                Cont.addError ('You Cannot delete the contacts of Indian accounts');

6            }

7            

8        }

9            

10    }

Regards,

Usha

 
3 answers
  1. Nov 20, 2015, 5:06 AM
    You are attempting to compare the Account's Country value by traversing the relationship to the Account record. This will only be available by querying for the contact records. Inside trigger.old, the value will be null.

    So if you include this line,

    List<Contact> contactList = [select Id, Account.Country__c from Contact where Id in :trigger.old];

    you will have the Account's Country value in a list of Contacts in your trigger.

    But you will not be able to use addError() on the rows retrieved via this SOQL statement. You will have to use addError() on the rows inside trigger.old or trigger.oldMap.

    By iterating over the contactList from the query, you can determine if any of the rows in your trigger have "India" as their Account's country, then you can use the Id to get the same record from trigger.oldMap and add the error to there.

    for (Contact cont : contactList) {

    if(cont.Account.country__c == 'India') {

    trigger.oldMap.get(cont.Id).addError ('You Cannot delete the contacts of Indian accounts');

    }

    }

    It's a very subtle error, easy to miss. I hope this helps!

Loading
0/9000