I'm stuck in the following issue:
there is a DB with Reference__c custom object with fields: AccountId, ContactId, IsPrimary(Boolean). There can be only one Reference with isPrimary=true for a one separate Contact.
A task is - when a user changes isPrimary value from False to True in a Reference object, a trigger must update the isPrimary value from True to False on one of related Reference records (last created, for example) with the same ContactId. At the same time user cannot update isPrimary value from True to False manually.
Is there a solution for this task so that I do not use a global static variable?
Currently, the update method in handler looks like:
public static void onAfterUpdate (Trigger.new, Trigger.oldMap) {
List<Reference__c> afterUpdateList = [SELECT Id, Name, isPrimary__c, Contact__c, CreatedDate FROM Reference__c ORDER BY CreatedDate DESC];
Set<Id> contIds = new Set<Id>();
for (Reference__c ref: Trigger.new) {
contIds.add(ref.Contact__c);
}
List<Reference__c> updateList = new List<Reference__c>();
for (Reference__c ref: Trigger.new) {
Boolean newContIsPrimary = ref.isPrimary__c;
Boolean oldContIsPrimary = oldMap.get(ref.Id).isPrimary__c;
if (!oldContIsPrimary && newContIsPrimary) {
for (Reference__c r: afterUpdateList) {
if (r.Id != ref.Id && r.Contact__c == ref.Contact__c && r.isPrimary__c) {
r.isPrimary__c = false;
updateList.add(r);
break;
}
}
} else if (oldContIsPrimary && !newContIsPrimary) {
ref.addError('UPDATE_TO_FALSE_ERROR_MESSAGE');
}
}
if (!updateList.isEmpty()) {
update updateList;
}
}
But it does not work properly as far as it does not distinct the context whether the user makes updates himself or the update is performed by the trigger.