Development questions

Write a trigger on Contact to ensure a single Account cannot have more than one "Primary Contact" (Is_Primary__c = true).

DevelopmentMediumCognizantInfosysEY

Use before insert, before update. Count primaries within the incoming batch and against existing primaries in the database.

apex
trigger ContactTrigger on Contact (before insert, before update) {
    Set<Id> accIds = new Set<Id>();
    for (Contact c : Trigger.new) if (c.Is_Primary__c && c.AccountId != null) accIds.add(c.AccountId);
    Set<Id> hasPrimary = new Set<Id>();
    for (Contact e : [SELECT AccountId FROM Contact WHERE AccountId IN :accIds
                      AND Is_Primary__c = true AND Id NOT IN :Trigger.new]) hasPrimary.add(e.AccountId);
    for (Contact c : Trigger.new) {
        if (c.Is_Primary__c && c.AccountId != null) {
            if (!hasPrimary.add(c.AccountId)) c.addError('Account already has a primary Contact.');
        }
    }
}

Adding to the set also catches duplicates inside the same batch.

apex-triggertriggercodingscenariovalidation