You need to sign in to do that
Don't have an account?
Evita DSouza
Fetch country value in apex trigger on Lead object in beforeInsert trigger
Hi,
I want to fetch country selected from picklist on Lead Object while creating a new Lead record. If Nothing is selected in country then default value should be Australia.
I wrote apex trigger in beforeInsert event to fetch selected country but it is always returning null and country is set to Australia even if user selects any country from picklist. Please help me to identify why null is returned
trigger LeadTrigger on Lead(beforeInsert){
for(Lead rec : Trigger.new){
if(rec.Country==null){
rec.Country='Australia';
}
}
}
I want to fetch country selected from picklist on Lead Object while creating a new Lead record. If Nothing is selected in country then default value should be Australia.
I wrote apex trigger in beforeInsert event to fetch selected country but it is always returning null and country is set to Australia even if user selects any country from picklist. Please help me to identify why null is returned
trigger LeadTrigger on Lead(beforeInsert){
for(Lead rec : Trigger.new){
if(rec.Country==null){
rec.Country='Australia';
}
}
}
Use the below code it is working fine for me:
// Trigger Code
trigger triggerOnLead on Lead (before insert) {
if(trigger.isBefore && trigger.isInsert){
SetCountrytriggerLead.SetCountrytriggerLead_method(trigger.New);
}
}
//Helper code
public class SetCountrytriggerLead {
public static void SetCountrytriggerLead_method(List<Lead> leadList){
for(Lead leadObj : leadList){
if(leadObj.Country == NULL){
leadObj.Country ='Australia';
}
}
}
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
I believe as Picklists are strings you should test for Empty rather than Null. Note that IsEmpty will check for Nulls also
And yes, it needs to be a before Insert or before Update for the field to be updated by the code.
HTH
Regards
Andrew
Also, make sure you actually have permissions to the country field as the user running the code. If you do not, then it will always be null.