function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Asel Vazir 1Asel Vazir 1 

First contact related to an account should be automatically marked as primary and with addition of next Contact the checkbox should be empty

Please help me to resolve my issue. I've created a trigger handler that populates 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. And I need the next Contact to be inserted without populated PrimaryContact checkbox:
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;


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

 
ANUTEJANUTEJ (Salesforce Developers) 
Hi Asel,

Although there could be multiple ways of doing this one such possible way I could think of is to get the account ids to the contacts that are newly added then run a soql query to get the count of contacts and in case if the count is zero then assign that particular contact as primary.

I hope this helps in case if this came in handy can you please choose this as the best answer so that it can be used by others in the future.

Regards,
Anutej