Skip to main content

Hello everyone,

in the accounts related contact, I want to make only one primary contact if the user wants to make another primary contact then it should throw an error. I wasn't able to validate the checkbox in line no 7.

 

#Apex Trigger

How to validate the checkbox in trigger?

3 answers
  1. Jul 5, 2021, 5:05 AM

    Hi Harshal,

     

     It's an Apex trigger for contact, so I don't think you need to search from your account.

     

    Here is an example of an Apex trigger for a contact created with other requirements.

     

    trigger AccOnePrimaryCon on Contact (before insert, before update) {

    Map<Id,Account> accMap = new Map<Id,Account> ([Select Id,Name, (Select Id, name, Is_Primary__c from Contacts) from Account

    Where Id in (Select AccountId from Contact where Id in :Trigger.new)]);

    List<Contact> conList = [Select Id, AccountId, Is_Primary__c from Contact where Id in :Trigger.new];

    for(Contact c: conList){

    if(c.Is_Primary__c == true && accMap.get(c.AccountId).Contacts.size()>0){

    for(Contact c2:accMap.get(c.AccountId).Contacts){

    if(c2.Is_Primary__c == true){

    c.addError('Account Already Can\'t have more than one Primary Contact! Already have One!');

    }

    }

    }

    }

    }

0/9000