i have the below scenario. One account is having many contacts. contact_status__c is a checkbox field on contact. i am trying to write a trigger which will check at least 1 contact should have this checkbox checked. if that account has one contact and if user makes the field uncheck, it should throw an error
Below code is not working.
'You are trying to remove last contact status checkbox which is not allowed'
trigger -
trigger checkaccount on contact(before insert, before update){
List<Id> accID = new List<Id>();
for(contact c : trigger.new){
if(c.accountId != null){
accID.add(c.accountId);
}
}
List<account> acc = [select id, (select id, contact_status__c from contacts where contact_status__c = true) from Account WHERE Id In: accID];
system.debug('@@@@acc ' + acc);
system.debug('@@@@acc ' + acc[0].contacts);
Map<id, boolean> bool = new map<id,boolean>();
for(Contact c : trigger.new){
if(acc.size() == 0 ) {
c.addError('You are trying to remove last contact status checkbox which is not allowed');
}
}
}