0

I am trying to build custom validation in my custom controller for a VF page. I have a field which is a multi select pick list. I would like to check if 'Other' is part of the list of values selected, and if yes, display an error. This is what I have done so far, based on my research:

if (acc.Donor_Interests__c.contains('Other') && acc.Donor_Interests_Other__c == null){
                ApexPages.Message myMsg = new ApexPages.Message(ApexPages.severity.ERROR, 'Please provide details of Donor Interests - Other in the field below.');
                ApexPages.addMessage(myMsg);
                return null;
}

In this case I get an error "Attempt to de-reference a null object"

2 Answers 2

4

You need to first check if it has any value, before parsing it to find specific values.

if (acc.Donor_Interests__c != null && ...)

I would adjust your approach as well though, to actually split on the selection delimiter (';'). To explain why, consider if your picklist had two options: Other and Other Option. If someone selects the latter, your current approach would consider Other to be selected, even though it is not. Instead, use the String.split method.

if (acc.Donor_Interests__c != null)
{
    List<String> selections = acc.Donor_Interests__c.split(';');
    if (selections.contains('Other') && acc.Donor_Interests_Other__c == null)
    {
        // bingo
    }
}
-1

With latest Salesforce updates, we can use safe navigation operator (?.) now for null check. Modifying your condition like this should help

if (acc.Donor_Interests__c?.contains('Other') && ...)
2
  • The Safe Navigation Operator (SNO) won't work in this scenario because when Donor_Interests__c is null, the SNO returns null. if(null && <other things>) is not valid syntax and I think you'd still end up with a Null Pointer Exception in this case.
    – Derek F
    Commented Aug 22, 2023 at 11:25
  • Also, the SNO was introduced in Winter '21 (API v50.0), so I wouldn't really say "latest" here.
    – Derek F
    Commented Aug 22, 2023 at 11:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .