+ Start a Discussion
Carrie Nunemaker 10Carrie Nunemaker 10 
I am completely new to Apex and could really use some help with what seems to be a simple task.  I have a formula on the contact, Persona_True__c, that returns a 1 if the custom field "persona" is populated and a 0 if it is blank.

I would like to have a roll-up summary that sums this field at the account level in a field called Related_Personas__c.  

Because we can't roll-up from contact to account I'm reading that this type of action needs to be a trigger, but I don't even know where to start.  Does anyone have any thoughts or expertise they can share to help me out? 
Best Answer chosen by Carrie Nunemaker 10
Anthony McDougaldAnthony McDougald
Good Evening Carrie,
Hope that your day is off to an amazing start. We've constructed a trigger to your specifications. Please test and report back if anything. Hope this helps and may God bless you abundantly.
trigger ContactSumTrigger on Contact (after delete, after insert, after undelete, after update) {

Contact[] cons;
    if (Trigger.isDelete){ 
    cons = Trigger.old;
    }
    else{
    cons = Trigger.new;
    }
Set<ID> acctIds = new Set<ID>();
for (Contact con : cons) {
   acctIds.add(con.AccountId);
}

Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([SELECT Id, AccountId, Persona_True__c FROM Contact WHERE AccountId IN :acctIds]);

Map<ID, Account> acctsToUpdate = new Map<ID, Account>([SELECT Id, Related_Personas__c FROM Account WHERE Id IN :acctIds]);

for (Account acct : acctsToUpdate.values()) {
Set<Id> conIds = new Set<Id>();
Decimal totalValue = 0;
for (Contact con : contactsForAccounts.values()) {
    if (con.AccountId == acct.Id && con.Persona_True__c != NULL) {
        totalValue += con.Persona_True__c; 
    }
}
acct.Related_Personas__c = totalValue;
}
if(acctsToUpdate.values().size() > 0) {
    update acctsToUpdate.values();
}
}


Best Regards,
Anthony McDougald
iKnowSFDCiKnowSFDC 

I have a list I need to sort by a primary key as well as a secondary key - I tried ORDER BY fieldName AND fieldNAME as well as ORDER BY fieldName AND BY fieldName - neither one compiled on save. 

 

Any ideas? 

 

Thanks!

 

JoAnn

Best Answer chosen by Admin (Salesforce Developers) 
craigmhcraigmh

Order By fieldName1, fieldName2

csbaacsbaa 

Hello Helper

 

I want to export   from an org a package  containing  custom objects,  Custom fields , classes,  custom buttons......

 

I created a package.xml  file where I included  the Metadata  types  I want to export

 

I can not  specify  Custom button Metadata  type

Looking into the salesforce docs it seems to me that is is  considered as weblink

 

I tried  something like  below

 

.....

<types>
<members>Account.CustomButton_1</members>
<members>Account.CustomButton_1</members>
<name>webLinks</name>
</types>

 

 

 

but it does not work

 

any suggestion?

 

 

Thanks in advance

Csaba

 

 

 

 

Best Answer chosen by csbaa
David CheungDavid Cheung
@csaba, meta data name for custom button is WebLink - in the singular form, you had it as WebLinks.
@Admin why was @Vinita_SFDC chosen as the best answer?
Kyle HavelkaKyle Havelka 
Hi All,

Let me preface this with a disclaimer. I am fairly new to SalesForce development. But I have 11 years experience as a developer.

I am working on a LWC that calls an Apex controller.

The Apex controller runs a fairly simple SOQL query against a custom object Move_Type__c. It has a master detail relationship with another Custom object Move_Goal_Type__c (see below)

Move_Type & Move_Goal_Type

Here is the query: 
[SELECT Name, Id
FROM pursue02__Move_Type__c
WHERE pursue02__Move_Goal_Type__r.Id = :movegoalTypeId ]
The variable comes into the controller (MoveTypeController) as an Id through a method getMoveTypesByMoveGoalTypeId which is decorated with @AuraEnabled(cacheable=true)

When I execute anonynmous, it works as expected, I get a list of Move_Type__c records with the Name and Id.

When the LWC calls it, it returns an empty array. Now I have debugged the method System.debug(movegoalTypeId) and it shows the correct value. And I assigned the SOQL results to a variable and output that as well, it shows values in the debug logs.

I have also checked the network traffic via chrome developer tools and it's sending the value as expected:
message: {
    "actions": [
        {
            "id": "815;a",
            "descriptor": "aura://ApexActionController/ACTION$execute",
            "callingDescriptor": "UNKNOWN",
            "params": {
                "namespace": "pursue02",
                "classname": "MoveTypeController",
                "method": "getMoveTypesByMoveGoalTypeId",
                "params": {
                    "goalTypeId": "a013k00000aWHa6AAG"
                },
                "cacheable": true,
                "isContinuation": false
            }
        }
    ]
}
But as I said it returns an empty array:
"actions": [
        {
            "id": "815;a",
            "state": "SUCCESS",
            "returnValue": {
                "returnValue": [],
                "cacheable": true
            },
            "error": []
        }
    ],
We have checked the permissions on both Move_Type__c and Move_Goal_Type__c, and they all appear to be correct.

Any one know what we are doing wrong? I'm scratching my head on this one.

Any help would be greatly appreciated!

 
Best Answer chosen by Kyle Havelka
Alain CabonAlain Cabon
  • Be careful to the used character case for the parameter goalTypeId even if Apex is not case sensitive but use preferably exactly the same values for the  parameters by copying/pasting the value between javascript and apex for the method name and the parameters.
  • You can try without cacheable=true
Timothy SmithTimothy Smith 
I am receiving the error:
Unexpected file found in package directory:
When I try to deploy a class that I have just created.  The file is saved in the /force-app/main/default/classes/Case_Trigger_Alert_Count.

I have also noticed that in the 'Problems' tab, I have the message:
The sourcepath ".../force-app/main/default/classes/Case_Trigger_Alert_Count" is not a valid source file path.  SourcePathInvalid [1,1]

The filename of the file I have just created and attempting to deploy is 'Case_Trigger_Alert_Count"
What am I missing to be able to deploy to my Sandbox?
Best Answer chosen by Timothy Smith
lnallurilnalluri
@Timothy

Ingeneral classes ends with .cls extension. Make sure you have that. Also every class should have meta xml file associated with it. 

For example
 SampleClass.cls
 
public with sharing class SampleClass {
// some code
}

SampleClass.cls-meta.xml
 
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>46.0</apiVersion>
    <status>Active</status>
</ApexClass>

Make sure you class has all these.

Thanks.
James Kacerguis 5James Kacerguis 5 
I currently have apex class in lightning component that is getting a specific Queue Id to assign as owner of the record the component is launched from.

This is the current  way I'm getting the id, but I'm guessing there is a better way to do this, any ideas?
Group marketingQueue = [SELECT id,Name FROM Group WHERE Type = 'Queue' and DeveloperNAME = 'MarketingProspectLeads'];
         	ID marketingQueueId = marketingQueue.id;
            //l.OwnerId = UserInfo.getUserId();
            system.debug('marketingQueue');
            l.OwnerId = marketingQueueId;

I just need to make sure this can't break so I'm assuming I should add some error checking or be doing this a different way.  Thanks in advance.  
Best Answer chosen by James Kacerguis 5
Sonali_takkeSonali_takke
Hi James,
If you don't require Name then you can modify your query as follows to reduce number of lines in code and add NULL check before assignment to avoid code break.
 
ID marketingQueueId = [SELECT id FROM Group WHERE Type = 'Queue' and DeveloperNAME = 'MarketingProspectLeads'].Id;

if(marketingQueueId != NULL) {
    l.OwnerId = marketingQueueId;
}

Kindly mark as resolved if you find this anser helpful. 
ismyhcismyhc 

I must be missing something..

 

The date is always 1 day behind when formating like so:

 

datetime xDate = o.campaign_start_date__c;
			
String xxDate = xDate.format('yyyy-dd-MM');
system.debug('sdate :' +xxDate);

 

I set the above field to 8/16/2011

 

and in debug it shows up as: 2011-15-08

 

Everytime I change it the debug value is shown as 1 day behind.. Im sure I could to +1, but could someone help me understand why this is happening?

 

Thanks!
Jacob Davis

Best Answer chosen by Admin (Salesforce Developers) 
Shashikant SharmaShashikant Sharma

This  is campaign_start_date__c  datetime field . And your users time zone must be such that GMT - some hours, so that GMT Offset makes a day less.

 

Try this

 

Datetime localTime = o.campaign_start_date__c.Date();
         
localTime = localTime.addHours(o.campaign_start_date__c.hour());
localTime = localTime.addMinutes(o.campaign_start_date__c.minute());
localTime = localTime.addSeconds(o.campaign_start_date__c.second());

String xxDate = xDate.format('yyyy-dd-MM');
system.debug('sdate :' +xxDate);

 

HNT_NeoHNT_Neo 
Hello, 

We have a class and trigger in place which is now producing the error listed below. It is referencing an Apex Class and an Apex Trigger of where the issue is stemming from. 

Can someone help me figure out how I can correct this? 

Thank you!
 
Apex script unhandled trigger exception by user/organization: 005A0000005XYZb/00DA0000033432M

triggerUpdAssignedLead: execution of BeforeUpdate

caused by: System.Exception: Too many SOQL queries: 101

Class.LeadTrigger.<init>: line 47, column 1
Trigger.triggerLead: line 3, column 1

Line 47  of the Class.LeadTrigger can be found in this class code below:  
for(User u : [Select Id, UserType, Contact.AccountId, Contact.Account.Member__c, Exclude_from_Zip_Placement__c From User Where isActive = true]){
 
public without sharing class LeadTrigger {
    //private static boolean alreadyExecuted = false;
    Private Set<String> OpenLeadStatus = new Set<String>{'Awaiting Decision','Initiating Contact','New', 'Quoting', 'Re-Engaged', 'Job Take'};
    Private String QuotingStatus = 'Quoting';
    Private String QuotingCampaignNumber = '34099';
    Private static String MODELER_LEAD = 'Modeler Lead';
    Private static String HOW_LEAD = 'Show Lead';
    Private static String STATUE = 'Statue';
    public static String ClosedStatus = 'Closed By EF';
    public static String ProjectDelayedStatus = 'Project Ending';
    //public static boolean isTest {get; set;}
    //public static boolean isTestUpdateLead {get; set;}
    public static boolean isUpdateLeadStatus {get; set;}
    public static boolean isUpdateHistoryLog {get; set;}
    
    //New class variable creatd for optimization - 10/2016
    //Prevent SOQL Query governor limit exception
    private Map<String,Id> recTypes = new Map<String,Id>();
    private final string queueInsideSalesId;
    private final string dummyCampaignId = null;
    private Map<Id, User> activeUsers = new Map<Id, User>();
    private Set<Id> excludedZipAssignUsers = new Set<Id>();
    
    //Creating class constructor to initialize class objects - 11/2017
    //Prevent SOQL Query governor limit exception
    public LeadTrigger(){
        //Retrieving RecordType information
        for(Schema.RecordTypeInfo rt : Lead.SObjectType.getDescribe().getRecordTypeInfos()){
            String rtName = rt.getName();
            if((rtName == MODELER_LEAD)||(rtName == SHOW_LEAD)){ 
                recTypes.put(rtName, rt.getRecordTypeId());
            }
        }
        
        //Retrieving values for the Lead Assignment - AssignLeads() method
        //Retrieving the default owner (Inside Sales Queue)
        for(QueueSobject queue : [Select QueueId From QueueSobject Where SobjectType = 'Assigned_Lead__c' and Queue.Name = 'Inside Sales']){
            queueInsideSalesId = queue.QueueId;
        }
        
        //Retrieving Dummy Campaign ID for Assigning New Leads to a Campaign
        for(Campaign c : [Select Id, Campaign_Number__c From Campaign Where Name Like '%Dummy%' Limit 1]){
            dummyCampaignId = c.Id;
        }
        
        // Retrieving Active Users List for Lead Assignment
        for(User u : [Select Id, UserType, Contact.AccountId, Contact.Account.Member__c, Exclude_from_Zip_Placement__c From User Where isActive = true]){
            //Retrieving Users excluded by Zip Assignment
            if(u.Exclude_from_Zip_Placement__c ==  true){
                excludedZipPlaceUsers.add(u.Id);
            }else{
                activeUsers.put(u.Id, u);
            }
        }
    }


This is the ApexTrigger code named referenced in the apex error code: 
Trigger.triggerLead: line 3, column 1
 
trigger triggerLead on Lead (after insert, before insert, before update, after update) {

    LeadTrigger lt = new LeadTrigger();
    if (Trigger.isInsert)
        lt.LeadInsertion(Trigger.New, Trigger.isBefore, Trigger.isAfter);
    else if (Trigger.isBefore)
        lt.LeadUpdate(Trigger.New, Trigger.old, Trigger.isBefore);
    
    if (Trigger.isAfter) {
      lt.ReassignALOnClosedLeads(Trigger.New, Trigger.old, null);
      lt.AddToCampaign(Trigger.New, Trigger.oldMap);
      lt.ProcessQuotingLeads(Trigger.New, Trigger.old);
    } else 
      lt.PopulateAmbassador(Trigger.New, Trigger.old);   
      
    
    // 10/22/2015 Ambassador enhancement Tia Xuan 
    if (Trigger.isBefore && Trigger.isUpdate){
      lt.CreateLastVisitTask(Trigger.new);
      lt.CopyHistoryLog(Trigger.new, Trigger.oldMap);   
    }
}





 
Best Answer chosen by HNT_Neo
Deepali KulshresthaDeepali Kulshrestha
Hi JH_Neo,

Greetings to you!

The following error appears when you exceed the Execution Governors Limit (you can run up to a total 100 SOQL queries in a single call or context). 

System.LimitException: Too many SOQL queries: 101 error

-Avoid SOQL queries that are inside FOR loops.

Try this code from line 47 in Class:
List<User> userList= [Select Id, UserType, Contact.AccountId, Contact.Account.Member__c, Exclude_from_Zip_Placement__c From User Where isActive = true];
for(User u : userList){
            //Retrieving Users excluded by Zip Assignment
            if(u.Exclude_from_Zip_Placement__c ==  true){
                excludedZipPlaceUsers.add(u.Id);
            }else{
                activeUsers.put(u.Id, u);
            }
        }

Notes:

All the SOQL queries in triggers fired from one call or context will be counted against the limit of 100.
Salesforce cannot disable or raise the Governors Limit.
Resolution    

Resolve the "Too many SOQL queries: 101" error
To fix the issue, change your code so that the number of SOQL fired is less than 100.

If you need to change the context, you can use @future annotation which will run the code asynchronously.
 

Best practices to avoid exceeding the Governors Limit
Since Apex runs on a multi-tenant platform, the Apex runtime engine strictly enforces limits to ensure code doesn't monopolize shared resources.
 

-Avoid SOQL queries that are inside FOR loops.
-Follow the key coding principals for Apex Code in our Developer's Guide.
-Review our best practices for Trigger and Bulk requests:
-Best practices for Triggers and Bulk requests (Force.com Apex Code Developer's Guide)


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
Cloud AtlasCloud Atlas 
Hi ,

Can some one help me to write a trigger to prevent delete of all Account records and its supporting test class.
Doesn't matter who the user is (Sys Admin/Custom Profile/Read Only...etc), the user should not be able to delete the account record.
There cannot be any exception.

Any help is appreciate.
Thanks!
A
Best Answer chosen by Cloud Atlas
Mohan_ShanmugamMohan_Shanmugam
Hi Ashish,

Here is the trigger which will prevent deletion of Account record.
trigger preventAccountDeletion on Account (before delete) {

    for(Account acc : trigger.old){
        acc.adderror('Account Cannot be deleted');
    }

}

TestClass for the above trigger would be
@isTest
private class testPreventAccountDeletion {
	
    static testmethod void testPreventAccDel(){
        Account accRecord = new Account(name='testAccount');
        insert accRecord;
        
        try{
            delete accRecord;
        }catch(DMLexception e){
            system.assert(e.getMessage().contains('Account Cannot be deleted'),'Account Cannot be deleted');                       
        }
    }
}

i did not get this - "There cannot be any exceptions"

with the above no user cannot delete a Account record, if attempted to do then a validation will thrown on a different page informing that account cannot de deleted. Below is the screensshot of error message.

User-added image
If you want the error to be in a differnt fashion then override the delete button with VF page as you like.

Hope this helps!

Thanks,
Mohan Shanmugam
 
Sfdc AdminSfdc Admin 
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 )
            {

            } 
  

        }
    

    }
 
Best Answer chosen by Sfdc Admin
Andrew GAndrew G
Hi again.  
If we consider the lack of coveage for clearValueOnContact

In your trigger it is only invoked on delete.  to bypass that criteria you would need a individual call as suggested by Nikhil
Add another test method to your class and try - you will need to flesh it out a little
@IsTest
static void test_clearValueOnContact()
{
	List<BusinessUnits__c> bus = new List<BusinessUnites__c>();
	//create other data - contact/user
	BusinessUnits__c bu = new BusinessUnits__c( Contact__c = cont.Id, LineOfBusiness__c = ' Agency',Sales_Rep__c = UserId );
	bus.add(bu);
	insert bus;
	BusinessUnitTriggerHandler.clearValueOnContact(bus);

//now SELECT contacts and assert that the fields are blank.


}
Try that for a start.
I will check back in a short while and give more suggestions.
Regards
Andrew