You need to sign in to do that
Don't have an account?
Faizan 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;
}
}
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;
}
}
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!
Please see the help article attached above for sample code
Let me know if it helps