A blog about Salesforce CRM Configuration and development

Saturday, 23 March 2019

Make only one record active at a time of same record type.


Scenario: Make only one contact record active at a time of the same record type on Account.

Solution: Using Apex Trigger: Create a trigger on the contact object for insert and update event. Find the code below.

 /* Name: deactivateContact  
  * Description: Make only one record active at a time of same record type.  
  * Created By: 23/03/2019  
  * Last ModifiedDate: 23/03/2019  
  * Created By: Arun Kumar  
 */  
 trigger deactivateContact on Contact (before update, before insert) {  
   if(Trigger.isBefore){  
     if(Trigger.isUpdate || Trigger.isInsert){  
        if(deactivateContactHelper.isFirstTime){ // check for recursive call  
         deactivateContactHelper.isFirstTime = false;  
         deactivateContactHelper.updateContact(Trigger.new);   
        }  
     }  
   }  
 }  

 /* Name:deactivateContactHelper  
  * Description: Update isActive field on contact( Only one contact record will be active at a time of same record type).  
  * Created Date: 23/03/2019  
  * Last ModifiedDate: 23/03/2019  
  * Created By: Arun Kumar  
 */  
 public class deactivateContactHelper {  
   public static boolean isFirstTime= true; // for recursive call check  
   // update isActive field ( Only one contact record will be active at a time of same record type).  
   public static void updateContact(List<Contact> contactList){   
     set<id> parentId = new set<id>();  
     set<id> recordId = new set<id>();  
     set<id> recordTypeIdSet = new set<Id>();  
     for(Contact c: contactList){  
       if(c.isActive__c){  
         parentId.add(c.AccountId); // accountid  
         recordId.add(c.id); // record id  
         recordTypeIdSet.add(c.recordTypeId); // recordtype id  
       }  
     }  
     List<contact> ContactForUpdate = new List<contact>(); // contact list for update  
     for(Contact con:[select id,isActive__c from contact where accountid IN: parentId and Id NOT IN: recordId and recordTypeId IN:recordTypeIdSet]){  
       con.isActive__c = false;// isActive__c = FALSE  
       ContactForUpdate.add(con);   
     }  
     if(ContactForUpdate.size()>0){  
       try{  
         update ContactForUpdate;// Update rest contact list  
       }  
       catch(Exception e){  
         system.debug('Exception has occred! ' +e.getMessage());  
       }  
     }   
   }  
 }  
Share:

0 comments:

Post a comment

Trailhead Profile


Follow by Email

Total Pageviews

Followers

Popular Posts

Powered by Blogger.

Contact form

Name

Email *

Message *