0

Please help me to resolve my issue. I've created a trigger handler that marks the Primary_Contact__c checkbox when inserting a new Contact on the Account without contacts. But when I try to create another Contact it continues to mark it as Primary.

public with sharing class PrimaryContactOnAccount {
public static void createFirstContactAsPrimaryContact(List<Contact> newContacts) {
    List<Account> accountsWithoutContacts = [SELECT Id, Name FROM Account WHERE Id NOT IN (SELECT AccountId FROM Contact)];

    for (Contact con : newContacts) {
        for (Account act : accountsWithoutContacts) {
            con.Primary_Contact__c = true;


                }
            }
        }

here is the Trigger for it:

 trigger ContactTrigger on Contact (after update,before insert, before update){
        if (Trigger.isBefore && Trigger.isInsert) {
            PrimaryContactOnAccount.createFirstContactAsPrimaryContact(Trigger.new);
    }

1 Answer 1

1

You're querying for every account in the database, not just the contacts in your trigger. Instead, you need to be more selective, and bulkify your code. This follows the extremely common aggregate-query-update pattern that you'll use in pretty much every trigger you ever write.

Here's what that looks like:

public class PrimaryContactOnAccount {
    public static void createFirstPrimaryContactAsPrimaryContact(Contact[] records) {
        // New Account Ids, Account Ids already marked with a primary contact
        Set<Id> accountIds = new Set<Id>(), existingIds = new Set<Id>();
        // Get account ids
        for(Contact record: records) {
            accountIds.add(record.AccountId);
        }
        // Get all account Ids that have a primary contact
        existingIds.addAll(new Map<Id, AggregateResult>([
            SELECT AccountId Id
            FROM Contact
            WHERE AccountId IN :accountIds AND Primary_Contact__c = TRUE
            GROUP BY AccountId
        ]).keySet());
        for(Contact record: records) {
            // If existingIds.add() returns true, there was no previous primary contact
            record.Primary_Contact__c = existingIds.add(record.AccountId);
        }
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .