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
JohnDuraiJohnDurai 

Making one primary contact for account

Hi - I have this scenario, One Account has multiple contacts and in Contact object we have field called Primary contact checkbox field.

If any one of the related contact  is true in  Primary contact checkbox field then other contacts shoud not have option to check that checkbox field.

Can someone suggest what will be the best solution for this and how we can proceed?
CharuDuttCharuDutt
Hii JohnDurai
Try Below Code
trigger PrimaryContact on Contact (before insert, before update) {
   set<id> getid = new set<id>();
    string contactId;
    List<Contact> conList = new List<Contact>();
    if(Trigger.isInsert || Trigger.isUpdate) {
        for(Contact cont: Trigger.New) {
            if(cont.Primary_Contact__c == true) {
                getid.add(cont.AccountId);
                contactId = cont.id;
            }
        }
    }
 
    List<contact> cList = [select id, Primary_Contact__c from contact where accountid IN: getid                                                   AND Primary_Contact__c = true];
 
    if(cList.size() > 0) {
        for(Contact newClst: cList) {
            if(newClst.id != contactId) {
                newClst.Primary_Contact__c = false;
                conList .add(newClst);
            }
        }
    }
    update conList;
  }
Please Mark It As Best Answer If It Helps
Thank You!