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
karthikeya 2karthikeya 2 

trigger code for Avoid multiple primary contact using checkbox

Take one checkbox on contact object.
Have only one primary contact from multiple contact in Account.
Avoid multiple primary contact from Trigger.
Anoop yadavAnoop yadav
Hi,

I think you can use the standard feature "Contact Roles".
In Account related List you will get this.
Hargobind_SinghHargobind_Singh
Contact Role on Account only allows you one primary contact. Can you elaborate your question a bit ? 

Vidhyasagaran MuralidharanVidhyasagaran Muralidharan
Same requirement i guess:).Check this post
https://developer.salesforce.com/forums/ForumsMain?id=906F0000000AbL6IAK
karthikeya 2karthikeya 2
the field is taken as check box not in tex box so check is true and should be selected only for the one contact

Nilu Lande 20Nilu Lande 20
trigger PrimaryContactValidate on Contact (before insert,before update) {

set<id> accIdSet = new set<id>();
for(Contact con : trigger.new){
    if(con.accountId!=null){
        if(trigger.isUpdate){
            Contact oldDetails=Trigger.oldMap.get(con.Id);
            if(con.IsPrimaryContact__c && !oldDetails.IsPrimaryContact__c){
                accIdSet.add(con.accountId);
            }
        }else{
            if(con.IsPrimaryContact__c){
                accIdSet.add(con.accountId);
            } 
        }
    }
}

if(accIdSet.size()>0){
    List<Contact> contactList=[select id,AccountId,IsPrimaryContact__c,FirstName,LastName from Contact where IsPrimaryContact__c=true and accountid in:accIdSet]; 
    
    //check if contact list has any value
    if(contactList!=null && contactList.size()>0)
    {
        map<id, list<contact>> accToContactListMap = new map<id, list<contact>>();
        for(Contact con: contactList){
            List<Contact> dummyConList = accToContactListMap.get(con.accountId);
            if(dummyConList == null){
                dummyConList = new list<contact>();
            }
            dummyConList.add(con);
            accToContactListMap.put(con.accountId, dummyConList);
        }
        
        system.debug('### accToContactListMap : '+accToContactListMap);
        for(id accId:accToContactListMap.keyset()){
            List<Contact> dummyConList = accToContactListMap.get(accId);
            
            if(dummyConList != null || dummyConList.size() >=0){
                Contact cont=dummyConList[0];
                trigger.new[0].addError('Primary contact already assgined to [ '+cont.FirstName+' '+cont.LastName +' ]. You can not change the primary contact.');
            }
        }
    }
}
}