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
Aviator517Aviator517 

Validating one record has checkbox checked

I'm trying to code (what would seem to be) a fairly simple trigger, but I keep getting hung up on how to conceptualize it.

 

There is a checkbox on contact called "Primary" for each account, I want to enforce that each account has one contact that is primary.

 

So, I want to enforce changing the primary by checking the box on the new contact, and the code go through and uncheck the previous primary record.

 

Then I want to run validation that will give an error if there are no contacts with it checked, or if there are two and display the error to the user. I'm assuming I would process the contacts being inserted or updated in a before trigger, then process validation in an after trigger. But, in the after trigger would it see the changes I made in the before trigger to know that a new contact has been made primary?

 

If someone could help me with the rough framework on what this would look like, I'd very much appreciate it!

 

Thanks.

souvik9086souvik9086

According to the Apex best practice it is better to add one trigger per object. So it is advised to add only before trigger in the contact.

 

Following trigger just shows the error display if more than one is marked as primary. Write rest conditions like this

 

trigger UpdateStatus on Contact(after insert,after update){

Integer countCheck;
List<Id> ids = new List<Id>();
List<Account> pObjList = new List<Account>();
for(Contact obj : Trigger.new){
ids.add(obj.AccountID);
}
pObjList = [SELECT ID, Name, (SELECT ID, Name, Primary__c FROM Contacts) FROM Account WHERE ID IN :ids];
for(Account pObj : pObjList){
countCheck = 0;
for(Contact cObj : pObj.Contacts){
if(cObj.Primary__c == TRUE){
countCheck++;
}
if(countCheck > 1){
cObj.Primary__c.addError('More than one contact is marked as Primary');
}
}
}
}

If this post is helpful please throw Kudos.If this post solves your problem kindly mark it as solution. Thanks
Aviator517Aviator517

Thanks for this! If i wantd to add functionality that was if I marked another contact as primary it would allow the change, and change the previous contact as not primary anymore  - would I have to do it in a before trigger? I'm assumining in the after trigger,  It wouldn't see the changes - right?