function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jon FoyJon Foy 

Apex Trigger Help, only one of the two fields I want to update is working.

I have the following Apex Trigger that is updating two fields on a custom object when saved.   The Case_Resource_ID__c field is being updated perfectly fine, but the Resource_Name__c field is not populating.  Here's the trigger:

trigger UpdateTimeSlip on Time_Slip__c (before insert, before update){
    Map<Id,Id> caseResourceMap = new Map<Id,Id>();
    String userId = userInfo.getUserId();
    String userName = userInfo.getName();
    Set<Id> caseIds = new Set<Id>();
   
    for(Time_Slip__c ts : trigger.new){
        caseIds.add(ts.Case__c);
    }
    for(Case_Resource__c caseResource : [select id,Case__c from Case_Resource__c where Resource_Name__c =: userId and Case__c IN: caseIds ]){
        caseResourceMap.put(caseResource.Case__c,caseResource.Id);  
    }
      
    List<Contact> contactList = [select id,Name from Contact where Name =: userId];

    for(Time_Slip__c ts : trigger.new){
        if(ts.Resource_Name__c != null){
            if(contactList[0].Id != null){
                ts.Resource_Name__c = contactList[0].Id;
            }
        }
        if(ts.Case_Resource_ID__c == null){
            if(caseResourceMap.containsKey(ts.Case__c) && caseResourceMap.get(ts.Case__c) !=null){
                ts.Case_Resource_ID__c = caseResourceMap.get(ts.Case__c);
            }
        }
    }
}
Best Answer chosen by Jon Foy
KaranrajKaranraj
Ahh.. I found the reason. In the If condition instead checking equal to null, you are checking not equal to null. 
       
if(ts.Resource_Name__c == null){
            if(contactList[0].Id != null){
                ts.Resource_Name__c = contactList[0].Id;
            }
      }


All Answers

KaranrajKaranraj
Jon - In the contact list query, instead of comparing user name, you are comparing with the id. so always your query return null value. Replace the contactlist query line

List<Contact> contactList = [select id,Name from Contact where Name =: userName Limit 1];


Jon FoyJon Foy
Resource_Name__c is still blank.
Jon FoyJon Foy
I checked the debug log and it's pulling the contact:
15:22:06.119 (119221199)|USER_DEBUG|[15]|DEBUG|contactList (Contact:{Name=Jon Foy, Id=003K000000qsa9YIAQ})

But I can't figure out why the field isn't updating.
KaranrajKaranraj
Ahh.. I found the reason. In the If condition instead checking equal to null, you are checking not equal to null. 
       
if(ts.Resource_Name__c == null){
            if(contactList[0].Id != null){
                ts.Resource_Name__c = contactList[0].Id;
            }
      }


This was selected as the best answer