2

I have to populate a Contact field programmatically according to the MailingCountry field in the before insert trigger so the contact is created properly. But I noticed that the field MailingCountry on Contact is populated in a weird way in the before trigger context; here's a sample trigger to reproduce the behaviour

trigger TR01_Contact on Contact (before insert, before update, after delete) {
    if(Trigger.IsBefore && Trigger.IsInsert)
    {
        for(Contact c : Trigger.new)
        {
            system.debug(JSON.serialize(c));
            system.debug(JSON.serialize(c.MailingCountry));
        }
    }
}

the output of this trigger is

contacts [{"attributes": {
"type": "Contact"
},
"Show_on_Account_Plan__c": false,
"IsDeleted": false,
"AccountId": "0011800000cLvVmAAK",
"Email": "nb@m.it",
"IsEmailBounced": false,
"DoNotCall": false,
"FirstName": "test",
"HasOptedOutOfEmail": false,
"HasOptedOutOfFax": false,
"SNPCAPIQ__Is_DB_USA_Data__c": false,
"CurrencyIsoCode": "USD",
"Salutation": "Mr.",
"pi__Needs_Score_Synced__c": false,
"OwnerId": "005f4000001LmWJAA0",
"MailingCountryCode": "IT",
"RecordTypeId": "012180000000YrGAAU",
"pi__pardot_hard_bounced__c": false,
"Contact_Summary_Ref__c": "a0318000008OUc8AAG",
"LastName": "test",
"Status__c": "Active",
"Prospecting_Stage__c": "New Contact",
"Opt_in__c": false

and

null

also MailingCountryCode is populated and if I go to the record page after the insertion I can see that MailingCountry is correctly displayed as "Italy"

I need a way to read MailingCountry or a way to retrieve the MailingCountry from the MailingCountryCode. Thanks!

3

If you have enabeled 'State and Country/Territory Picklists' in your org use the below code to get country details. Please don't add inside for loop.

Schema.DescribeFieldResult fieldResult = User.Countrycode.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
Map<String,String> countryMap = new Map<String,String>();
for( Schema.PicklistEntry f : ple){
    System.debug(f.getLabel() +'::'+ f.getValue());
    countryMap.put(f.getValue(), f.getLabel());
}

You will get country code from c.MailingCountryCode.

Use countryMap.get(c.MailingCountryCode) to get country name.

Else you may need to used Custom Metadata Type or Custom Setting to store country code and label accordingly and access this whenever as needed.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.