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
Vidya H 4Vidya H 4 

Trigger which will not allow any users to delete Contact that named as Primary contact.


  for example - if Account has 3 related contacts such as contact a, contact b and Primary contact.
The contact with name primary contact should not be deleted by any user. Remaning contacts can be deleted.
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Vidya,

You can use the below trigger and handler.

Trigger:
trigger DeleteContact on Contact (before delete) {
    if(Trigger.isdelete && trigger.isbefore){
        
        DeleteContactHandler d= new DeleteContactHandler();
        d.deletecontact(Trigger.old);
    }
}

Handler:
public class DeleteContactHandler {

    public void deletecontact(List<Contact> conlist){
        for(Contact c: conlist){
            system.debug('contact'+c);
            SYSTEM.debug('NAME'+c.name);
            if(c.FirstName=='Primary' && c.LastName=='Contact' ){
                c.adderror('you cannot delete primary contact');
            }
        }
    }
}

If this solution helps, Please mark it as best answer.

Thanks,