I am trying to limit an Account to have only one Primary Contact (with a small twist).
What I would like to do is, If Contact A is already Primary, and a user goes in selects Contact B as Primary, then I want to have Contact B as Primary, and no longer have Contact A as Primary.
How could I go about doing that?
I have this following code:
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, Primary__c from contacts where Primary__c = true) from Account WHERE Id In: accID];
Map<id, boolean> bool = new map<id,boolean>();
for(account a : acc){
bool.put(a.id, a.contacts.size()>0 ? true : false);
}
for(Contact c : trigger.new){
if(bool.get(c.AccountId) == true){
c.addError('no more primary fields');
}
}
}