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
himanshu huske 7himanshu huske 7 

Please help me with trigger code

Only One contact should be primary under Account.If user makes other contact as primary then previous one should be made non- primary.Need to store the new and old primary contact value on 2 fields oldContact and newContact on Account.
 
Best Answer chosen by himanshu huske 7
ANUTEJANUTEJ (Salesforce Developers) 
Hi Himanshu,

You could try using the below code and let me know if there are any issues:
Link: http://salesforcemaniacs.blogspot.com/2016/01/primary-contact-trigger-in-salesforce.html
trigger PrimaryContact on Contact (before insert, before update) {
 
   set<id> getid = new set<id>();
    string contactId;
    List<Contact> conList = new List<Contact>();
 
    // Trigger Functionality
    if(Trigger.isInsert || Trigger.isUpdate) {
     
        for(Contact cont: Trigger.New) {
         
            if(cont.Primary_Contact__c == true) {
             
                getid.add(cont.AccountId);
                contactId = cont.id;
            }
        }
    }
 
    // Fetching the other Contact which has primary contact checked
    List<contact> cList = [select id, Primary_Contact__c from contact where accountid IN: getid                                                   AND Primary_Contact__c = true];
 
    // Unchecking the already checked primary contact
    if(cList.size() > 0) {
     
        for(Contact newClst: cList) {
         
            if(newClst.id != contactId) {
             
                newClst.Primary_Contact__c = false;
                conList .add(newClst);
            }
        }
    }
    update conList;
  }

I hope this helps and in case if this comes handy can you please choose this as best answer so that it can be useful for others in the future.


Regards,
Anutej