• Sfdc Admin
  • NEWBIE
  • 10 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 5
    Questions
  • 6
    Replies
public class SuperCloneService {
    public Id doClone(String parentId) {
        Set<String> querySobject = new Set<String>();
        for(Super_Clone_Objects__mdt m : [select Id, DeveloperName, Label, API_Name__c 
                                          from Super_Clone_Objects__mdt  ]){ 
                                              querySobject.add(m.API_Name__c) ;  
                                          }
        Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        String objectAPIName = '';
        String keyPrefix = parentId.substring(0,3);
        for( Schema.SObjectType obj : schemaMap.Values() ){
            String prefix = obj.getDescribe().getKeyPrefix();
            if(prefix == keyPrefix){
                objectAPIName = obj.getDescribe().getName();
                break;
            }
        }
        Set <String> fieldMap = schemaMap.get(objectAPIName).getDescribe().fields.getMap().keySet();
        List<String> finalFields = new List<String>() ;
        finalFields.addAll(fieldMap);
        
        SObjectType objToken = Schema.getGlobalDescribe().get(objectAPIName); 
        DescribeSObjectResult objDef = objToken.getDescribe();
        Map<String,String> so = new Map<String,String>();
        Map<String,String> so1 = new Map<String,String>();
        
        for (Schema.ChildRelationship cr: objDef.getChildRelationships()) 
        {
            if(cr.getField().getDescribe().isAccessible()&& cr.getField().getDescribe().isCreateable()&&cr.getField().getDescribe().isAccessible() && cr.getRelationshipName()!=null){
                if(querySobject.contains(''+cr.getChildSObject())){
                    so.put(''+cr.getChildSObject()  , ''+cr.getRelationshipName());
                    so1.put(''+cr.getRelationshipName()  , ''+cr.getField());
                }
            }
        } 
        
        List<String> subqueries = prepareSubqueries(so, schemaMap);
        String query =
            'SELECT ' + String.join(finalFields, ',')+
            ','+String.join(subqueries, ',') +
            ' FROM ' +objectAPIName +
            ' WHERE Id = \''+parentId+'\'';
        
        List<Sobject> parentObj = Database.query(query);
        Sobject parentRecordId = parentObj[0];
        
        Sobject clonedRecord = parentRecordId.clone();
        insert clonedRecord;
        List<sObject> childObjects =cloneChildren(parentRecordId, clonedRecord, so  ,so1);
        insert childObjects;
        List<Attachment> attachmentsToInsert = new List<Attachment>();
        insert attachmentsToInsert;
        System.debug('clonedRecord'+clonedRecord.Id);
        return clonedRecord.Id ;
        
    }
    
    private List<sObject> cloneChildren(
        Sobject parent,
        Sobject child,
        Map<String , String> childRelatedListObjects,
        Map<String , String> childRelatedListObjects1
    ){
        
        List<sObject> childObjects = new List<SObject>();
        for (String childObjectDefinition : childRelatedListObjects.values()) {
            List<sObject> parentRecords = parent.getSObjects(childObjectDefinition);
            System.debug('parentRecords'+parentRecords);
            if (parentRecords != null) {
                List<sObject> records = parentRecords.deepClone();
                System.debug('records'+records);
                for (sObject record : records) {
                    record.put(childRelatedListObjects1.get(childObjectDefinition), child.Id);
                }
                childObjects.addAll(records);
            }
        }
        return childObjects;
    }
    
    private List<String> prepareSubqueries(
        Map<String , String> childrelatedListObjects,
        Map <String, Schema.SObjectType> schemaMap
    ){
        List<String> subqueries = new List<String>();
        for(String childObject : childrelatedListObjects.keySet()){
            List<String> childFields = new List<String>();
            Map <String, Schema.SObjectField> fieldMap = schemaMap.get(childObject).getDescribe().fields.getMap();
            System.debug('fieldMap'+fieldMap);
            for(Schema.SObjectField sof : fieldMap.values()){
                DescribeFieldResult dfr = sof.getDescribe();
                if(dfr.isCreateable()){
                    childFields.add(dfr.getName());
                }
            }
            if(!childFields.isEmpty()){
                String query = '(SELECT ' + String.join(childFields, ',') + ' FROM ' + childrelatedListObjects.get(childObject) + ')';
                subqueries.add(query);
            }
            
        }
        return subqueries;
    }
    
}
Hello Everyone,
Can anyone help me with the testclass for above code.?

Thank you.
Hi Everyone,
I have a requirement to deep clone/ super clone a custom object with it's related lists (related lists includes chatter), and attachments links that directs to original attachment( don't want to duplicate attachments). For this requirement I used a custom code that supports on any sobject but, it's doing just basic clone not deep/super clone.

Please see below:
 
public class CloneSingleRecord {
    @AuraEnabled
    public static String cloneAnySobjet(String recordId){
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        
          List<Attachment> attachments = new List<Attachment>();
          list<Attachment> attachlist = new list<Attachment>();
          
        String objectAPIName = '';
        String keyPrefix = recordId.substring(0,3);
        for( Schema.SObjectType obj : schemaMap.Values() ){
            String prefix = obj.getDescribe().getKeyPrefix();
            if(prefix == keyPrefix){
                objectAPIName = obj.getDescribe().getName();
                break;
            }
        }
        Set <String> fieldMap = schemaMap.get(objectAPIName).getDescribe().fields.getMap().keySet();
        String soqlQuery = 'SELECT ' ; 
        for (String s :fieldMap ){
            if(schema.getGlobalDescribe().get(objectAPIName).getDescribe().fields.getMap().get(s).getDescribe().isAccessible()){
                soqlQuery +=  + s+',';
            }
        }
        soqlQuery =  soqlQuery.removeEnd(',');
        soqlQuery += ' FROM ' +objectAPIName +' WHERE ID = \'' + recordId +'\'' ;
        System.debug('soqlQuery'+soqlQuery);
        SObject record = Database.query(soqlQuery);
        SObject clondedParentRecordID= record.clone(false, true, true, false);
        try{
            insert clondedParentRecordID ;
            return clondedParentRecordID.id ;
        }catch(Exception e){
            return '' ;
        }
           }
}
How can I modify this code to get my requirement done ?

 
Hello Everyone,
I got a requirement to crete new visualforce page in Lightning for one custom object, I have used HTML (div and slds) to build the page. Now my next requirement is to add HelpText for all 25 fields, Initially I was in a assumption that I can create one Visualforce component and use that for all the fields in Apex page. Please find my Component below
<apex:component selfClosing="true">
    <apex:attribute name="helpText" description="Help Text." type="String" required="true"/>
   <script>
        var div = document.createElement('div');
        div.innerHTML = '<div class="body">{!helpText}</div>';
        setTimeout(function() {
            var searchInvoiceHelperText = document.getElementById('searchInvoiceHelperText').appendChild(div);
        }, 1000);
    </script>
    <div class="mouseOverInfoOuter" id="searchInvoiceHelper" onfocus="addMouseOver(this)" onmouseover="addMouseOver(this)" tabindex="0">
        <img src="/s.gif" alt="" class="infoIcon" title="" />
        <div class="mouseOverInfo" id="searchInvoiceHelperText" style="display: none; opacity: -0.19999999999999996; left: 16px;">
            
        </div>
    </div>
</apex:component>
But when I used this component for one field it's working fine, and when I use this for two fields only one field is showing helptext with description and other field is having icon with no description.
<div
                        class="slds-form-element__row ma-ltss-font_style slds-p-top_xxx-small slds-p-left_small">
                        <div class="slds-size_1-of-5">
                        <label class="evv-slds-form-element__label">User Story Status <c:helpicon helpText="Used to identify the stage of this story within the SprintUser Story."/></label>
                        </div>
User-added image

If I use the same icon for next field then:
User-added image

 
User-added image




In  visualforce code I have included place holder but output has only richtext editor. I have tried for other fields too but I was able to show either rich text editor or HTML placeholder. My requirement is to include both richtext editor and Html place holder on long description fields.

Please find my Code below:
<div 
class="slds-form-element__row ma-ltss-font_style  slds-p-top_xxx-small 
slds-p-left_small ">
<div class="slds-size_1-of-5  ">
 <label class="evv-slds-form-element__label">Acceptance Criteria/Future State </label>
</div>
<div class="slds-size_1-of-2 mh-ltss-requiredInput">
<div class="mh-ltss-requiredBlock"></div>
<div class="slds-form-element__control">
<apex:inputTextarea richText="true"    
value="{!UserStory__c.Acceptance_Criteria__c}" html-placeholder="Give  a brief description of user impact"  style="width: 250Px; height: 
150px;"/>
</div>
</div>
</div>



 
Here is my class:

public with sharing class BusinessUnitTriggerHandler 
{
    public static void checkDuplicate(List<BusinessUnits__c> units, Map<Id, BusinessUnits__c> oldMap, Boolean isInsert ) 
    {
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();

      // Get System Admin profile Id
      Id profileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1].Id;
      System.debug('UAC: profileId' + profileId);

      //Get current User Profile ID
      Id userProfileId = UserInfo.getProfileId() ;
    System.debug('UAC: userProfileId' + userProfileId);

    // Iterate over all business records 
        for( BusinessUnits__c bu : units )
        {  
          // When current user Non-Admin OR these fields are updated 
          if(  profileId != userProfileId &&
            ( isInsert || ( !isInsert && ( bu.LineOfBusiness__c != oldMap.get(bu.Id).LineOfBusiness__c || bu.Contact__c != oldMap.get(bu.Id).Contact__c))) ) 
          {
            lineOfBusiness.add(bu.LineOfBusiness__c);
            contactIds.add(bu.Contact__c);
            unitsToProcess.add(bu);
            businessUnitMap.put(bu.LineOfBusiness__c+bu.Contact__c, 0);
          }
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Get existing Business records 
        for( BusinessUnits__c bu : [SELECT Id, LineOfBusiness__c, Contact__c FROM BusinessUnits__c 
                      WHERE Contact__c IN :contactIds AND LineOfBusiness__c IN :lineOfBusiness AND ID NOT IN :units ])
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          businessUnitMap.put( key, (businessUnitMap.get(key)+1) ) ;
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Iterate again over inserted/updated records 
        for( BusinessUnits__c bu : unitsToProcess )
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          // When Already exists then show error
          if( businessUnitMap.containsKey(key) && businessUnitMap.get(key) > 0 ) bu.addError('Sorry. A Business Relationship for this Business Unit already exists for this Contact.');
        }
    }

    public static void changeOwner(List<BusinessUnits__c> units )
    {
        for(BusinessUnits__c bu : units )
        {
            if( bu.Sales_Rep__c != null && bu.OwnerId != bu.Sales_Rep__c  ) bu.OwnerId = bu.Sales_Rep__c ; 
        }
    }

    public static Map<String, BusinessUnitRulesManagement__c> lobAndUserRoleToBusinessUnitCS
    {
        get
        {
            if(lobAndUserRoleToBusinessUnitCS == null )
            {
                lobAndUserRoleToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    lobAndUserRoleToBusinessUnitCS.put( cs.LineofBusiness__c + '' + cs.RoleDeveloperName__c, cs);
                }
            }
            //for(String key : lobAndUserRoleToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobAndUserRoleToBusinessUnitCS.get(key) );
            return lobAndUserRoleToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    updateContactFromCS()
    *   @Purpose:   When BusinessUnit is Updated then update SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static Boolean RUN_ONCE_UCFCS = true ; 
    public static void updateContactFromCS(List<BusinessUnits__c> units, Map<Id,BusinessUnits__c> oldMap, Boolean isInsert )
    {
        System.debug('UAC: BU updateContactFromCS START ' );
        Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
        Map<Id,Contact> existingContacts = new Map<Id,Contact>();
        Set<Id> contactIdsAddedForUpdate = new Set<Id>();
        List<Contact> contactsToUpdate = new List<Contact>();
        Set<Id> contactIds = new Set<Id>();
        Set<Id> userIds = new Set<Id>();
        Map<Id, String> userIdToUserRole = new Map<Id, String>();

        for(BusinessUnits__c bu : units)
        {
            BusinessUnits__c old =  !isInsert ? oldMap.get(bu.Id) : NULL ; 
            if( isInsert || ( !isInsert && (bu.Sales_Rep__c != old.Sales_Rep__c || bu.Escrow_Officer__c != old.Escrow_Officer__c)) ) 
            {
                if(bu.Sales_Rep__c != null ) userIds.add(bu.Sales_Rep__c);
                if(bu.Escrow_Officer__c != null && bu.Sales_Rep__c != bu.Escrow_Officer__c ) userIds.add(bu.Escrow_Officer__c);
                businessUnitToContactId.put(bu, bu.Contact__c);
                contactIds.add(bu.Contact__c);
            }
        }
        System.debug('UAC: businessUnitToContactId ' + businessUnitToContactId );

        for(User u : [SELECT Id, UserRole.DeveloperName FROM User WHERE ID IN :userIds ])
        {
            userIdToUserRole.put(u.Id, u.UserRole.DeveloperName );
        }
        System.debug('UAC: userIdToUserRole ' + userIdToUserRole );
        
        for(Contact con : Database.query( 'SELECT ' + getFields('Contact') + ' FROM Contact WHERE ID IN :contactIds ') )
        {
            existingContacts.put(con.Id, con);
        }

        for(BusinessUnits__c bu : businessUnitToContactId.keyset() )
        {
            String validUserRole = 
                //ContactTriggerHandler.currentUserRole == 'Administration' && 
                userIdToUserRole.containsKey(bu.Sales_Rep__c) ? userIdToUserRole.get(bu.Sales_Rep__c) : ContactTriggerHandler.currentUserRole ;

            // When no custom setting found for current User Role then Go Back
            if(!lobAndUserRoleToBusinessUnitCS.containsKey(bu.LineOfBusiness__c + '' + validUserRole)) continue ; 

            // Get Custom setting record
            BusinessUnitRulesManagement__c cs = lobAndUserRoleToBusinessUnitCS.get(bu.LineOfBusiness__c + '' + validUserRole);
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 
            
            // Get related Contact 
            Contact con = existingContacts.get(businessUnitToContactId.get(bu));

            // When SalesRep or EscrowOfficer changed 
            if((bu.Sales_Rep__c != con.get(cs.SalesRepFieldonContactAPIName__c) || bu.Escrow_Officer__c != con.get(cs.EscrowOfficerFieldonContactAPIName__c) ) 
                    && !contactIdsAddedForUpdate.contains(con.Id) )
            {
                contactIdsAddedForUpdate.add(con.Id);
                Contact newContact = new Contact();
                newContact.Id = con.Id;
                System.debug('UAC: bu.Sales_Rep__c ' + bu.Sales_Rep__c );
                System.debug('UAC: bu.Escrow_Officer__c ' + bu.Escrow_Officer__c );
                if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) newContact.put(cs.SalesRepFieldonContactAPIName__c, bu.Sales_Rep__c);
                if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) newContact.put(cs.EscrowOfficerFieldonContactAPIName__c, bu.Escrow_Officer__c);
                contactsToUpdate.add(newContact);
            } 
        }

        System.debug('UAC: contactsToUpdate ' + contactsToUpdate );

        // Update Contacts 
        if(contactsToUpdate.size() > 0 ) 
        {
            ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = false ;
            update contactsToUpdate ;
            ContactTriggerHandler.RUN_ONCE_UBUFCS = true ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = true ;
        }

        System.debug('UAC: BU updateContactFromCS END ' );
    
    }

    /**
    *   @Method:    getFields()
    *   @Purpose:   Use to get all fields of passing object  
    *   @Param:     String objName for which you want to get fields
    *   @Return:    Comma seprated fields
    *   @Date:      05/18/2017
    *
    *   @Updates: 
    */
    private static String getFields(String objectName)
    {
        //Broke this out of formatQuery because it could be used separately
        String fields = '';
        
        // Get All Objects List
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        
        // Get object detail which passed as argument
        SObjectType objectType = gd.get(objectName);

        // Get passed object detail
        Schema.DescribeSObjectResult r = objectType.getDescribe();

        //Get all fields for passed object 
        Map<String, Schema.SObjectField> fieldMap = r.fields.getMap();

        // Itterate over all fields and check one by one 
        for (String f: fieldMap.keySet())
        { 
            // Get current field 
            Schema.SObjectField sof = fieldMap.get(f);
            // Get current field detail
            Schema.DescribeFieldResult dfr = sof.getDescribe();

            // when current field is accessible, creatable and defaultonCreare then concatinate in field string
            if( dfr.isAccessible() )
            {
                String fname = dfr.getName(); 
                fields += fname + ', '; 
            }
        }
        
        // remove last comma
        fields = fields.substring(0, fields.length() - 2);
        return fields;
    }


    public static Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS
    {
        get
        {
            if(lobToBusinessUnitCS == null )
            {
                lobToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    if(!lobToBusinessUnitCS.containsKey(cs.LineofBusiness__c)) lobToBusinessUnitCS.put( cs.LineofBusiness__c, cs);
                }
            }
            //for(String key : lobToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobToBusinessUnitCS.get(key) );
            return lobToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    clearValueOnContact()
    *   @Purpose:   When BusinessUnit is Updated then update and clearOut SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static void clearValueOnContact(List<BusinessUnits__c> units)
    {
        System.debug('UAC: BU clearValueOnContact START ' );
     
        
     
        Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();

        // Iterate over BusinessUnit 
        for(BusinessUnits__c bu : units )
        {
            if(bu.Contact__c != null) contactIdToLOB.put(bu.Contact__c, bu.LineOfBusiness__c);
        }
        System.debug('UAC: BU contactIdToLOB ' + contactIdToLOB );
        if(contactIdToLOB.size() == 0) 
           return ; 

        // Get related Contacts 
        contacts = new Map<Id, Contact>( [SELECT Id FROM Contact WHERE ID IN :contactIdToLOB.keyset() ]);

        // Iterate over ContactIds 
        for(Id contactId : contactIdToLOB.keyset() )
        {   
            // Get Custom Setting Business Unit
            BusinessUnitRulesManagement__c cs = lobToBusinessUnitCS.get(contactIdToLOB.get(contactId));
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 

            // Get Contact 
            Contact con = contacts.get(contactId);

            // Clear Out Values on Contact 
            if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) con.put(cs.SalesRepFieldonContactAPIName__c, null);
            if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) con.put(cs.EscrowOfficerFieldonContactAPIName__c, null);
            System.debug('UAC: con ' + con );
        }

        // Update Contact
        ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;
        update contacts.values() ;
        ContactTriggerHandler.RUN_ONCE_UBUFCS = true ; 

        System.debug('UAC: BU clearValueOnContact End ' );
    }

}

Test class:

@isTest
private class BusinessUnitTriggerHandlerTest 
{
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();
      Set<Id> userIds = new Set<Id>();
      Map<Id, String> userIdToUserRole = new Map<Id, String>();
     Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
     Map<Id,Contact> existingContacts = new Map<Id,Contact>();
     Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS;
       Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();
    static testMethod void testCheckDuplicate() 
    {
         
   
        Profile profile = [Select Id from Profile where name = 'ORT Direct Sales User'];
        //UserRole ur = [Select Id from UserRole where UserRole.DeveloperName = 'Central_Direct_Agency'];

        User nonAdminUser = new User( ProfileId = profile.Id, Username = System.now().millisecond() + 'test2@test.com.dev',UserRoleId = '00E1G000000IWzyUAG',
                                    Alias = 'batman', Email='bruce.wayne@wayneenterprises.com', EmailEncodingKey='UTF-8',Firstname='Bruce',
                                    Lastname='Wayne',LanguageLocaleKey='en_US',LocaleSidKey='en_US',TimeZoneSidKey='America/Chicago' );
        System.runAs(new User( Id = UserInfo.getUserId() ))
        {
            Database.insert(nonAdminUser);
        }

        Account acc = TestUtility.createAccount( TestUtility.default_account_rt, false );
        acc.Name = 'sfdcpoint';
        acc.Account_Status__c = 'Active';
        acc.AccountNumber = '001';
        insert acc; 
    
        System.runAs(nonAdminUser)
        {
            Contact cont = TestUtility.createContact( TestUtility.default_contact_rt , acc, false ); 
            cont.MailingStreet = 'Test Street' ;
            cont.MailingCity = 'Minneapolis';
            cont.MailingState = 'MN';
            cont.MailingPostalCode = '55347';
            cont.MailingCountry = 'United States' ; 
            insert cont;
            
            
            BusinessUnitRulesManagement__c cs = new BusinessUnitRulesManagement__c();
            cs.Name = 'AgencyManager';
            cs.EscrowOfficerFieldonContactAPIName__c = 'Text';
            cs.LineofBusiness__c = 'testlob';
            cs.RoleDeveloperName__c = 'uniquetest';
            cs.SalesRepFieldonContactAPIName__c = 'conttext';
            cs.Status__c = 'alltext';
            insert cs;
            Id userId = UserInfo.getUserId() ;
          

            BusinessUnits__c bu = new BusinessUnits__c( Contact__c = cont.Id, LineOfBusiness__c = ' Agency',Sales_Rep__c = UserId );
          
            insert bu ; 
  
            try
            {
                BusinessUnits__c bu1 = new BusinessUnits__c( Contact__c = cont.Id,LineOfBusiness__c = 'Western Title Division',Sales_Rep__c = UserId  );
                insert bu1 ;  
            }
            catch(DmlException de )
            {

            } 
  

        }
    

    }
 
Here is my class:

public with sharing class BusinessUnitTriggerHandler 
{
    public static void checkDuplicate(List<BusinessUnits__c> units, Map<Id, BusinessUnits__c> oldMap, Boolean isInsert ) 
    {
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();

      // Get System Admin profile Id
      Id profileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1].Id;
      System.debug('UAC: profileId' + profileId);

      //Get current User Profile ID
      Id userProfileId = UserInfo.getProfileId() ;
    System.debug('UAC: userProfileId' + userProfileId);

    // Iterate over all business records 
        for( BusinessUnits__c bu : units )
        {  
          // When current user Non-Admin OR these fields are updated 
          if(  profileId != userProfileId &&
            ( isInsert || ( !isInsert && ( bu.LineOfBusiness__c != oldMap.get(bu.Id).LineOfBusiness__c || bu.Contact__c != oldMap.get(bu.Id).Contact__c))) ) 
          {
            lineOfBusiness.add(bu.LineOfBusiness__c);
            contactIds.add(bu.Contact__c);
            unitsToProcess.add(bu);
            businessUnitMap.put(bu.LineOfBusiness__c+bu.Contact__c, 0);
          }
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Get existing Business records 
        for( BusinessUnits__c bu : [SELECT Id, LineOfBusiness__c, Contact__c FROM BusinessUnits__c 
                      WHERE Contact__c IN :contactIds AND LineOfBusiness__c IN :lineOfBusiness AND ID NOT IN :units ])
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          businessUnitMap.put( key, (businessUnitMap.get(key)+1) ) ;
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Iterate again over inserted/updated records 
        for( BusinessUnits__c bu : unitsToProcess )
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          // When Already exists then show error
          if( businessUnitMap.containsKey(key) && businessUnitMap.get(key) > 0 ) bu.addError('Sorry. A Business Relationship for this Business Unit already exists for this Contact.');
        }
    }

    public static void changeOwner(List<BusinessUnits__c> units )
    {
        for(BusinessUnits__c bu : units )
        {
            if( bu.Sales_Rep__c != null && bu.OwnerId != bu.Sales_Rep__c  ) bu.OwnerId = bu.Sales_Rep__c ; 
        }
    }

    public static Map<String, BusinessUnitRulesManagement__c> lobAndUserRoleToBusinessUnitCS
    {
        get
        {
            if(lobAndUserRoleToBusinessUnitCS == null )
            {
                lobAndUserRoleToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    lobAndUserRoleToBusinessUnitCS.put( cs.LineofBusiness__c + '' + cs.RoleDeveloperName__c, cs);
                }
            }
            //for(String key : lobAndUserRoleToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobAndUserRoleToBusinessUnitCS.get(key) );
            return lobAndUserRoleToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    updateContactFromCS()
    *   @Purpose:   When BusinessUnit is Updated then update SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static Boolean RUN_ONCE_UCFCS = true ; 
    public static void updateContactFromCS(List<BusinessUnits__c> units, Map<Id,BusinessUnits__c> oldMap, Boolean isInsert )
    {
        System.debug('UAC: BU updateContactFromCS START ' );
        Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
        Map<Id,Contact> existingContacts = new Map<Id,Contact>();
        Set<Id> contactIdsAddedForUpdate = new Set<Id>();
        List<Contact> contactsToUpdate = new List<Contact>();
        Set<Id> contactIds = new Set<Id>();
        Set<Id> userIds = new Set<Id>();
        Map<Id, String> userIdToUserRole = new Map<Id, String>();

        for(BusinessUnits__c bu : units)
        {
            BusinessUnits__c old =  !isInsert ? oldMap.get(bu.Id) : NULL ; 
            if( isInsert || ( !isInsert && (bu.Sales_Rep__c != old.Sales_Rep__c || bu.Escrow_Officer__c != old.Escrow_Officer__c)) ) 
            {
                if(bu.Sales_Rep__c != null ) userIds.add(bu.Sales_Rep__c);
                if(bu.Escrow_Officer__c != null && bu.Sales_Rep__c != bu.Escrow_Officer__c ) userIds.add(bu.Escrow_Officer__c);
                businessUnitToContactId.put(bu, bu.Contact__c);
                contactIds.add(bu.Contact__c);
            }
        }
        System.debug('UAC: businessUnitToContactId ' + businessUnitToContactId );

        for(User u : [SELECT Id, UserRole.DeveloperName FROM User WHERE ID IN :userIds ])
        {
            userIdToUserRole.put(u.Id, u.UserRole.DeveloperName );
        }
        System.debug('UAC: userIdToUserRole ' + userIdToUserRole );
        
        for(Contact con : Database.query( 'SELECT ' + getFields('Contact') + ' FROM Contact WHERE ID IN :contactIds ') )
        {
            existingContacts.put(con.Id, con);
        }

        for(BusinessUnits__c bu : businessUnitToContactId.keyset() )
        {
            String validUserRole = 
                //ContactTriggerHandler.currentUserRole == 'Administration' && 
                userIdToUserRole.containsKey(bu.Sales_Rep__c) ? userIdToUserRole.get(bu.Sales_Rep__c) : ContactTriggerHandler.currentUserRole ;

            // When no custom setting found for current User Role then Go Back
            if(!lobAndUserRoleToBusinessUnitCS.containsKey(bu.LineOfBusiness__c + '' + validUserRole)) continue ; 

            // Get Custom setting record
            BusinessUnitRulesManagement__c cs = lobAndUserRoleToBusinessUnitCS.get(bu.LineOfBusiness__c + '' + validUserRole);
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 
            
            // Get related Contact 
            Contact con = existingContacts.get(businessUnitToContactId.get(bu));

            // When SalesRep or EscrowOfficer changed 
            if((bu.Sales_Rep__c != con.get(cs.SalesRepFieldonContactAPIName__c) || bu.Escrow_Officer__c != con.get(cs.EscrowOfficerFieldonContactAPIName__c) ) 
                    && !contactIdsAddedForUpdate.contains(con.Id) )
            {
                contactIdsAddedForUpdate.add(con.Id);
                Contact newContact = new Contact();
                newContact.Id = con.Id;
                System.debug('UAC: bu.Sales_Rep__c ' + bu.Sales_Rep__c );
                System.debug('UAC: bu.Escrow_Officer__c ' + bu.Escrow_Officer__c );
                if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) newContact.put(cs.SalesRepFieldonContactAPIName__c, bu.Sales_Rep__c);
                if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) newContact.put(cs.EscrowOfficerFieldonContactAPIName__c, bu.Escrow_Officer__c);
                contactsToUpdate.add(newContact);
            } 
        }

        System.debug('UAC: contactsToUpdate ' + contactsToUpdate );

        // Update Contacts 
        if(contactsToUpdate.size() > 0 ) 
        {
            ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = false ;
            update contactsToUpdate ;
            ContactTriggerHandler.RUN_ONCE_UBUFCS = true ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = true ;
        }

        System.debug('UAC: BU updateContactFromCS END ' );
    
    }

    /**
    *   @Method:    getFields()
    *   @Purpose:   Use to get all fields of passing object  
    *   @Param:     String objName for which you want to get fields
    *   @Return:    Comma seprated fields
    *   @Date:      05/18/2017
    *
    *   @Updates: 
    */
    private static String getFields(String objectName)
    {
        //Broke this out of formatQuery because it could be used separately
        String fields = '';
        
        // Get All Objects List
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        
        // Get object detail which passed as argument
        SObjectType objectType = gd.get(objectName);

        // Get passed object detail
        Schema.DescribeSObjectResult r = objectType.getDescribe();

        //Get all fields for passed object 
        Map<String, Schema.SObjectField> fieldMap = r.fields.getMap();

        // Itterate over all fields and check one by one 
        for (String f: fieldMap.keySet())
        { 
            // Get current field 
            Schema.SObjectField sof = fieldMap.get(f);
            // Get current field detail
            Schema.DescribeFieldResult dfr = sof.getDescribe();

            // when current field is accessible, creatable and defaultonCreare then concatinate in field string
            if( dfr.isAccessible() )
            {
                String fname = dfr.getName(); 
                fields += fname + ', '; 
            }
        }
        
        // remove last comma
        fields = fields.substring(0, fields.length() - 2);
        return fields;
    }


    public static Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS
    {
        get
        {
            if(lobToBusinessUnitCS == null )
            {
                lobToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    if(!lobToBusinessUnitCS.containsKey(cs.LineofBusiness__c)) lobToBusinessUnitCS.put( cs.LineofBusiness__c, cs);
                }
            }
            //for(String key : lobToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobToBusinessUnitCS.get(key) );
            return lobToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    clearValueOnContact()
    *   @Purpose:   When BusinessUnit is Updated then update and clearOut SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static void clearValueOnContact(List<BusinessUnits__c> units)
    {
        System.debug('UAC: BU clearValueOnContact START ' );
     
        
     
        Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();

        // Iterate over BusinessUnit 
        for(BusinessUnits__c bu : units )
        {
            if(bu.Contact__c != null) contactIdToLOB.put(bu.Contact__c, bu.LineOfBusiness__c);
        }
        System.debug('UAC: BU contactIdToLOB ' + contactIdToLOB );
        if(contactIdToLOB.size() == 0) 
           return ; 

        // Get related Contacts 
        contacts = new Map<Id, Contact>( [SELECT Id FROM Contact WHERE ID IN :contactIdToLOB.keyset() ]);

        // Iterate over ContactIds 
        for(Id contactId : contactIdToLOB.keyset() )
        {   
            // Get Custom Setting Business Unit
            BusinessUnitRulesManagement__c cs = lobToBusinessUnitCS.get(contactIdToLOB.get(contactId));
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 

            // Get Contact 
            Contact con = contacts.get(contactId);

            // Clear Out Values on Contact 
            if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) con.put(cs.SalesRepFieldonContactAPIName__c, null);
            if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) con.put(cs.EscrowOfficerFieldonContactAPIName__c, null);
            System.debug('UAC: con ' + con );
        }

        // Update Contact
        ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;
        update contacts.values() ;
        ContactTriggerHandler.RUN_ONCE_UBUFCS = true ; 

        System.debug('UAC: BU clearValueOnContact End ' );
    }

}

Test class:

@isTest
private class BusinessUnitTriggerHandlerTest 
{
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();
      Set<Id> userIds = new Set<Id>();
      Map<Id, String> userIdToUserRole = new Map<Id, String>();
     Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
     Map<Id,Contact> existingContacts = new Map<Id,Contact>();
     Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS;
       Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();
    static testMethod void testCheckDuplicate() 
    {
         
   
        Profile profile = [Select Id from Profile where name = 'ORT Direct Sales User'];
        //UserRole ur = [Select Id from UserRole where UserRole.DeveloperName = 'Central_Direct_Agency'];

        User nonAdminUser = new User( ProfileId = profile.Id, Username = System.now().millisecond() + 'test2@test.com.dev',UserRoleId = '00E1G000000IWzyUAG',
                                    Alias = 'batman', Email='bruce.wayne@wayneenterprises.com', EmailEncodingKey='UTF-8',Firstname='Bruce',
                                    Lastname='Wayne',LanguageLocaleKey='en_US',LocaleSidKey='en_US',TimeZoneSidKey='America/Chicago' );
        System.runAs(new User( Id = UserInfo.getUserId() ))
        {
            Database.insert(nonAdminUser);
        }

        Account acc = TestUtility.createAccount( TestUtility.default_account_rt, false );
        acc.Name = 'sfdcpoint';
        acc.Account_Status__c = 'Active';
        acc.AccountNumber = '001';
        insert acc; 
    
        System.runAs(nonAdminUser)
        {
            Contact cont = TestUtility.createContact( TestUtility.default_contact_rt , acc, false ); 
            cont.MailingStreet = 'Test Street' ;
            cont.MailingCity = 'Minneapolis';
            cont.MailingState = 'MN';
            cont.MailingPostalCode = '55347';
            cont.MailingCountry = 'United States' ; 
            insert cont;
            
            
            BusinessUnitRulesManagement__c cs = new BusinessUnitRulesManagement__c();
            cs.Name = 'AgencyManager';
            cs.EscrowOfficerFieldonContactAPIName__c = 'Text';
            cs.LineofBusiness__c = 'testlob';
            cs.RoleDeveloperName__c = 'uniquetest';
            cs.SalesRepFieldonContactAPIName__c = 'conttext';
            cs.Status__c = 'alltext';
            insert cs;
            Id userId = UserInfo.getUserId() ;
          

            BusinessUnits__c bu = new BusinessUnits__c( Contact__c = cont.Id, LineOfBusiness__c = ' Agency',Sales_Rep__c = UserId );
          
            insert bu ; 
  
            try
            {
                BusinessUnits__c bu1 = new BusinessUnits__c( Contact__c = cont.Id,LineOfBusiness__c = 'Western Title Division',Sales_Rep__c = UserId  );
                insert bu1 ;  
            }
            catch(DmlException de )
            {

            } 
  

        }
    

    }
 
Hi Everyone,
I have a requirement to deep clone/ super clone a custom object with it's related lists (related lists includes chatter), and attachments links that directs to original attachment( don't want to duplicate attachments). For this requirement I used a custom code that supports on any sobject but, it's doing just basic clone not deep/super clone.

Please see below:
 
public class CloneSingleRecord {
    @AuraEnabled
    public static String cloneAnySobjet(String recordId){
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        
          List<Attachment> attachments = new List<Attachment>();
          list<Attachment> attachlist = new list<Attachment>();
          
        String objectAPIName = '';
        String keyPrefix = recordId.substring(0,3);
        for( Schema.SObjectType obj : schemaMap.Values() ){
            String prefix = obj.getDescribe().getKeyPrefix();
            if(prefix == keyPrefix){
                objectAPIName = obj.getDescribe().getName();
                break;
            }
        }
        Set <String> fieldMap = schemaMap.get(objectAPIName).getDescribe().fields.getMap().keySet();
        String soqlQuery = 'SELECT ' ; 
        for (String s :fieldMap ){
            if(schema.getGlobalDescribe().get(objectAPIName).getDescribe().fields.getMap().get(s).getDescribe().isAccessible()){
                soqlQuery +=  + s+',';
            }
        }
        soqlQuery =  soqlQuery.removeEnd(',');
        soqlQuery += ' FROM ' +objectAPIName +' WHERE ID = \'' + recordId +'\'' ;
        System.debug('soqlQuery'+soqlQuery);
        SObject record = Database.query(soqlQuery);
        SObject clondedParentRecordID= record.clone(false, true, true, false);
        try{
            insert clondedParentRecordID ;
            return clondedParentRecordID.id ;
        }catch(Exception e){
            return '' ;
        }
           }
}
How can I modify this code to get my requirement done ?

 
Here is my class:

public with sharing class BusinessUnitTriggerHandler 
{
    public static void checkDuplicate(List<BusinessUnits__c> units, Map<Id, BusinessUnits__c> oldMap, Boolean isInsert ) 
    {
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();

      // Get System Admin profile Id
      Id profileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1].Id;
      System.debug('UAC: profileId' + profileId);

      //Get current User Profile ID
      Id userProfileId = UserInfo.getProfileId() ;
    System.debug('UAC: userProfileId' + userProfileId);

    // Iterate over all business records 
        for( BusinessUnits__c bu : units )
        {  
          // When current user Non-Admin OR these fields are updated 
          if(  profileId != userProfileId &&
            ( isInsert || ( !isInsert && ( bu.LineOfBusiness__c != oldMap.get(bu.Id).LineOfBusiness__c || bu.Contact__c != oldMap.get(bu.Id).Contact__c))) ) 
          {
            lineOfBusiness.add(bu.LineOfBusiness__c);
            contactIds.add(bu.Contact__c);
            unitsToProcess.add(bu);
            businessUnitMap.put(bu.LineOfBusiness__c+bu.Contact__c, 0);
          }
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Get existing Business records 
        for( BusinessUnits__c bu : [SELECT Id, LineOfBusiness__c, Contact__c FROM BusinessUnits__c 
                      WHERE Contact__c IN :contactIds AND LineOfBusiness__c IN :lineOfBusiness AND ID NOT IN :units ])
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          businessUnitMap.put( key, (businessUnitMap.get(key)+1) ) ;
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Iterate again over inserted/updated records 
        for( BusinessUnits__c bu : unitsToProcess )
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          // When Already exists then show error
          if( businessUnitMap.containsKey(key) && businessUnitMap.get(key) > 0 ) bu.addError('Sorry. A Business Relationship for this Business Unit already exists for this Contact.');
        }
    }

    public static void changeOwner(List<BusinessUnits__c> units )
    {
        for(BusinessUnits__c bu : units )
        {
            if( bu.Sales_Rep__c != null && bu.OwnerId != bu.Sales_Rep__c  ) bu.OwnerId = bu.Sales_Rep__c ; 
        }
    }

    public static Map<String, BusinessUnitRulesManagement__c> lobAndUserRoleToBusinessUnitCS
    {
        get
        {
            if(lobAndUserRoleToBusinessUnitCS == null )
            {
                lobAndUserRoleToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    lobAndUserRoleToBusinessUnitCS.put( cs.LineofBusiness__c + '' + cs.RoleDeveloperName__c, cs);
                }
            }
            //for(String key : lobAndUserRoleToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobAndUserRoleToBusinessUnitCS.get(key) );
            return lobAndUserRoleToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    updateContactFromCS()
    *   @Purpose:   When BusinessUnit is Updated then update SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static Boolean RUN_ONCE_UCFCS = true ; 
    public static void updateContactFromCS(List<BusinessUnits__c> units, Map<Id,BusinessUnits__c> oldMap, Boolean isInsert )
    {
        System.debug('UAC: BU updateContactFromCS START ' );
        Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
        Map<Id,Contact> existingContacts = new Map<Id,Contact>();
        Set<Id> contactIdsAddedForUpdate = new Set<Id>();
        List<Contact> contactsToUpdate = new List<Contact>();
        Set<Id> contactIds = new Set<Id>();
        Set<Id> userIds = new Set<Id>();
        Map<Id, String> userIdToUserRole = new Map<Id, String>();

        for(BusinessUnits__c bu : units)
        {
            BusinessUnits__c old =  !isInsert ? oldMap.get(bu.Id) : NULL ; 
            if( isInsert || ( !isInsert && (bu.Sales_Rep__c != old.Sales_Rep__c || bu.Escrow_Officer__c != old.Escrow_Officer__c)) ) 
            {
                if(bu.Sales_Rep__c != null ) userIds.add(bu.Sales_Rep__c);
                if(bu.Escrow_Officer__c != null && bu.Sales_Rep__c != bu.Escrow_Officer__c ) userIds.add(bu.Escrow_Officer__c);
                businessUnitToContactId.put(bu, bu.Contact__c);
                contactIds.add(bu.Contact__c);
            }
        }
        System.debug('UAC: businessUnitToContactId ' + businessUnitToContactId );

        for(User u : [SELECT Id, UserRole.DeveloperName FROM User WHERE ID IN :userIds ])
        {
            userIdToUserRole.put(u.Id, u.UserRole.DeveloperName );
        }
        System.debug('UAC: userIdToUserRole ' + userIdToUserRole );
        
        for(Contact con : Database.query( 'SELECT ' + getFields('Contact') + ' FROM Contact WHERE ID IN :contactIds ') )
        {
            existingContacts.put(con.Id, con);
        }

        for(BusinessUnits__c bu : businessUnitToContactId.keyset() )
        {
            String validUserRole = 
                //ContactTriggerHandler.currentUserRole == 'Administration' && 
                userIdToUserRole.containsKey(bu.Sales_Rep__c) ? userIdToUserRole.get(bu.Sales_Rep__c) : ContactTriggerHandler.currentUserRole ;

            // When no custom setting found for current User Role then Go Back
            if(!lobAndUserRoleToBusinessUnitCS.containsKey(bu.LineOfBusiness__c + '' + validUserRole)) continue ; 

            // Get Custom setting record
            BusinessUnitRulesManagement__c cs = lobAndUserRoleToBusinessUnitCS.get(bu.LineOfBusiness__c + '' + validUserRole);
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 
            
            // Get related Contact 
            Contact con = existingContacts.get(businessUnitToContactId.get(bu));

            // When SalesRep or EscrowOfficer changed 
            if((bu.Sales_Rep__c != con.get(cs.SalesRepFieldonContactAPIName__c) || bu.Escrow_Officer__c != con.get(cs.EscrowOfficerFieldonContactAPIName__c) ) 
                    && !contactIdsAddedForUpdate.contains(con.Id) )
            {
                contactIdsAddedForUpdate.add(con.Id);
                Contact newContact = new Contact();
                newContact.Id = con.Id;
                System.debug('UAC: bu.Sales_Rep__c ' + bu.Sales_Rep__c );
                System.debug('UAC: bu.Escrow_Officer__c ' + bu.Escrow_Officer__c );
                if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) newContact.put(cs.SalesRepFieldonContactAPIName__c, bu.Sales_Rep__c);
                if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) newContact.put(cs.EscrowOfficerFieldonContactAPIName__c, bu.Escrow_Officer__c);
                contactsToUpdate.add(newContact);
            } 
        }

        System.debug('UAC: contactsToUpdate ' + contactsToUpdate );

        // Update Contacts 
        if(contactsToUpdate.size() > 0 ) 
        {
            ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = false ;
            update contactsToUpdate ;
            ContactTriggerHandler.RUN_ONCE_UBUFCS = true ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = true ;
        }

        System.debug('UAC: BU updateContactFromCS END ' );
    
    }

    /**
    *   @Method:    getFields()
    *   @Purpose:   Use to get all fields of passing object  
    *   @Param:     String objName for which you want to get fields
    *   @Return:    Comma seprated fields
    *   @Date:      05/18/2017
    *
    *   @Updates: 
    */
    private static String getFields(String objectName)
    {
        //Broke this out of formatQuery because it could be used separately
        String fields = '';
        
        // Get All Objects List
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        
        // Get object detail which passed as argument
        SObjectType objectType = gd.get(objectName);

        // Get passed object detail
        Schema.DescribeSObjectResult r = objectType.getDescribe();

        //Get all fields for passed object 
        Map<String, Schema.SObjectField> fieldMap = r.fields.getMap();

        // Itterate over all fields and check one by one 
        for (String f: fieldMap.keySet())
        { 
            // Get current field 
            Schema.SObjectField sof = fieldMap.get(f);
            // Get current field detail
            Schema.DescribeFieldResult dfr = sof.getDescribe();

            // when current field is accessible, creatable and defaultonCreare then concatinate in field string
            if( dfr.isAccessible() )
            {
                String fname = dfr.getName(); 
                fields += fname + ', '; 
            }
        }
        
        // remove last comma
        fields = fields.substring(0, fields.length() - 2);
        return fields;
    }


    public static Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS
    {
        get
        {
            if(lobToBusinessUnitCS == null )
            {
                lobToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    if(!lobToBusinessUnitCS.containsKey(cs.LineofBusiness__c)) lobToBusinessUnitCS.put( cs.LineofBusiness__c, cs);
                }
            }
            //for(String key : lobToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobToBusinessUnitCS.get(key) );
            return lobToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    clearValueOnContact()
    *   @Purpose:   When BusinessUnit is Updated then update and clearOut SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static void clearValueOnContact(List<BusinessUnits__c> units)
    {
        System.debug('UAC: BU clearValueOnContact START ' );
     
        
     
        Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();

        // Iterate over BusinessUnit 
        for(BusinessUnits__c bu : units )
        {
            if(bu.Contact__c != null) contactIdToLOB.put(bu.Contact__c, bu.LineOfBusiness__c);
        }
        System.debug('UAC: BU contactIdToLOB ' + contactIdToLOB );
        if(contactIdToLOB.size() == 0) 
           return ; 

        // Get related Contacts 
        contacts = new Map<Id, Contact>( [SELECT Id FROM Contact WHERE ID IN :contactIdToLOB.keyset() ]);

        // Iterate over ContactIds 
        for(Id contactId : contactIdToLOB.keyset() )
        {   
            // Get Custom Setting Business Unit
            BusinessUnitRulesManagement__c cs = lobToBusinessUnitCS.get(contactIdToLOB.get(contactId));
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 

            // Get Contact 
            Contact con = contacts.get(contactId);

            // Clear Out Values on Contact 
            if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) con.put(cs.SalesRepFieldonContactAPIName__c, null);
            if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) con.put(cs.EscrowOfficerFieldonContactAPIName__c, null);
            System.debug('UAC: con ' + con );
        }

        // Update Contact
        ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;
        update contacts.values() ;
        ContactTriggerHandler.RUN_ONCE_UBUFCS = true ; 

        System.debug('UAC: BU clearValueOnContact End ' );
    }

}

Test class:

@isTest
private class BusinessUnitTriggerHandlerTest 
{
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();
      Set<Id> userIds = new Set<Id>();
      Map<Id, String> userIdToUserRole = new Map<Id, String>();
     Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
     Map<Id,Contact> existingContacts = new Map<Id,Contact>();
     Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS;
       Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();
    static testMethod void testCheckDuplicate() 
    {
         
   
        Profile profile = [Select Id from Profile where name = 'ORT Direct Sales User'];
        //UserRole ur = [Select Id from UserRole where UserRole.DeveloperName = 'Central_Direct_Agency'];

        User nonAdminUser = new User( ProfileId = profile.Id, Username = System.now().millisecond() + 'test2@test.com.dev',UserRoleId = '00E1G000000IWzyUAG',
                                    Alias = 'batman', Email='bruce.wayne@wayneenterprises.com', EmailEncodingKey='UTF-8',Firstname='Bruce',
                                    Lastname='Wayne',LanguageLocaleKey='en_US',LocaleSidKey='en_US',TimeZoneSidKey='America/Chicago' );
        System.runAs(new User( Id = UserInfo.getUserId() ))
        {
            Database.insert(nonAdminUser);
        }

        Account acc = TestUtility.createAccount( TestUtility.default_account_rt, false );
        acc.Name = 'sfdcpoint';
        acc.Account_Status__c = 'Active';
        acc.AccountNumber = '001';
        insert acc; 
    
        System.runAs(nonAdminUser)
        {
            Contact cont = TestUtility.createContact( TestUtility.default_contact_rt , acc, false ); 
            cont.MailingStreet = 'Test Street' ;
            cont.MailingCity = 'Minneapolis';
            cont.MailingState = 'MN';
            cont.MailingPostalCode = '55347';
            cont.MailingCountry = 'United States' ; 
            insert cont;
            
            
            BusinessUnitRulesManagement__c cs = new BusinessUnitRulesManagement__c();
            cs.Name = 'AgencyManager';
            cs.EscrowOfficerFieldonContactAPIName__c = 'Text';
            cs.LineofBusiness__c = 'testlob';
            cs.RoleDeveloperName__c = 'uniquetest';
            cs.SalesRepFieldonContactAPIName__c = 'conttext';
            cs.Status__c = 'alltext';
            insert cs;
            Id userId = UserInfo.getUserId() ;
          

            BusinessUnits__c bu = new BusinessUnits__c( Contact__c = cont.Id, LineOfBusiness__c = ' Agency',Sales_Rep__c = UserId );
          
            insert bu ; 
  
            try
            {
                BusinessUnits__c bu1 = new BusinessUnits__c( Contact__c = cont.Id,LineOfBusiness__c = 'Western Title Division',Sales_Rep__c = UserId  );
                insert bu1 ;  
            }
            catch(DmlException de )
            {

            } 
  

        }
    

    }
 
Hi,
How to write a test class for the apex which is fetching data and displaying.
Thanks