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
Evita DSouzaEvita 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';
}
}
}
Tad Aalgaard 3Tad Aalgaard 3
Change beforeInsert to before insert.
 
trigger LeadTrigger on Lead(before insert){

 
Evita DSouzaEvita DSouza
@Tad Yes, changed the event name still it’s giving same issue.....country is not being set properly 
Ajay K DubediAjay K Dubedi
Hi Evita

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
Andrew GAndrew G
Try using the String.IsEmpty method.

I believe as Picklists are strings you should test for Empty rather than Null.  Note that IsEmpty will check for Nulls also
 
if (Trigger.isBefore) {
  for (Lead rec : Trigger.new) {
    if (String.isEmpty(rec.Country)) {
        rec.Country = 'Australia';
    }
  }
}

And yes, it needs to be a before Insert or before Update for the field to be updated by the code. 

HTH
Regards
Andrew​​​​​​​
Tad Aalgaard 3Tad Aalgaard 3
Make sure the country field is actually the country field and not some second country field with the same label but different API,

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.