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
Faizan Ali 24Faizan Ali 24 

How to not make trigger work if this condition is not met

Hi All,

I have a trigger that autofills a lookup field based on a picklist value. It will look for the Contact name when a person is selected from the picklist.

However, whenever a person is not selected from picklist it should not fire the trigger. When I do try to I get this error:

Autofill: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.Autofill: line 6, column 1



trigger Autofill on Event (before insert, before update) {   
    
        for (Event e : Trigger.new) 
        {              
            String [] str = e.Appointment_with__c.split(' ');
            
            
            List<Contact> cont = [SELECT Id FROM Contact WHERE FirstName =:str[0] AND LastName =:str[1]];              
            
            
            e.Staff__c = cont[0].Id;
        }
}
AnudeepAnudeep (Salesforce Developers) 
This error is caused by a line of code that is trying to use an object that has not been instantiated or an object's attribute that has not been initialized

See this help article to learn more

I recommend doing a size check before using cont list (cont[0]) to fix this issue. 

You can also make use of Safe Navigation Operator to learn more

Let me know if this helps. If it does, please mark this answer as Best. It may help others in the community. Thank You!

 
Faizan Ali 24Faizan Ali 24
Could you give me example for my code. I do not understand :/
AnudeepAnudeep (Salesforce Developers) 
Can you try with the following code?
 
List<Contact> cont = [SELECT Id FROM Contact WHERE FirstName =:str[0] AND LastName =:str[1]];              
            
            
    if(Cont.size()>1) {
            e.Staff__c = cont[0].Id;
}

Please see the help article attached above for sample code

Let me know if it helps