You need to sign in to do that
Don't have an account?
Ching Hory
Trigger error help..!!!
trigger Avoidduplicateprimarycontact on Contact(before insert , before update){ Map<ID,Contact> accountIds = new Map<ID,Contact>(); for(Contact c : Trigger.New){ accountIds.put(c.AccountId,c); } for(Account acc : [Select Id , (Select Id, priority__c from Contacts) From Account Where Id IN :accountIds.keyset()]) { for(Contact con : acc.contacts) { if(accountIds.get(acc.Id).priority__c == 'Primary') { if(con.priority__c == 'Primary') { con.adderror('There is already one primary contact exists.'); } } }}}
Try this code:
Trigger:
trigger Avoidduplicateprimarycontact on Contact (before insert , before update) {
if((trigger.Isinsert && trigger.Isbefore) || (trigger.Isupdate && trigger.Isbefore)) {
Avoidduplicateprimarycontact_handler.checkPrimaryContact(trigger.new);
}
}
Trigger Handler:
public class Avoidduplicateprimarycontact_handler {
public static void checkPrimaryContact(List<Contact> conList) {
try {
system.debug('conList------' + conList);
Map<ID, Contact> accountIdVsContactMap = new Map<ID, Contact>();
Set<Id> accIdSet = new Set<Id>();
List<Contact> newConList = new List<Contact>();
for(Contact con : conList) {
if(con.AccountId != null) {
accIdSet.add(con.AccountId);
}
}
system.debug('accIdSet------' + accIdSet);
if(accIdSet.size() > 0) {
newConList = [SELECT Id, priority__c, AccountId from Contact WHERE AccountId IN : accIdSet LIMIT 10000];
}
system.debug('newConList------' + newConList);
if(newConList.size() > 0) {
for(Contact co : newConList) {
if(!accountIdVsContactMap.ContainsKey(co.AccountId)) {
accountIdVsContactMap.put(co.AccountId, co);
}
}
}
system.debug('accountIdVsContactMap------' + accountIdVsContactMap);
for(Contact co : conList) {
if(accountIdVsContactMap.containsKey(co.AccountId) && accountIdVsContactMap.get(co.AccountId).priority__c == 'Primary') {
system.debug('------inside if------');
co.adderror('There is already one primary contact exists.');
}
}
} catch(Exception e) {
System.debug('The following exception has occurred: ' + e.getMessage());
System.debug('The following Line : ' + e.getLineNumber());
}
}
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi