[SalesForce] Compare field value to list of values in Visualforce ‘Required’ parameter

I'm looking for a way to simplify my 'Required' parameter on my VF page fields.

For example, I want my 'Account' field to be required if one of a half dozen 'Activity' options are selected.

Currently, I have to write out the comparison to each possible value within the visualforce parameter itself, eg:

<apex:inputfield value="{!entry.Account__c}" required="{!(entry.Activity__c == 'option 1' || entry.Activity__c == 'option 2' || ... etc)}" />

This is very cumbersome even with evaluating only a single field's options… imagine if it had to be determined from the combined values of multiple fields!

So now I'm wondering: Is it possible to compare a parameter value to a LIST of values?

Say in my controller I defined a list of strings of Activity field options. Could I do something SOQL-ish like this?:

<apex:inputfield value="{!entry.Account__c}" required="{!(entry.Activity__c IN :valueListFromController)}" />

Best Answer

Just use a Set whitelist and add a Boolean property.

static final Set<String> whitelist = new Set<String> { 'option 1', 'option 2', 'etc.' };
public Boolean isAccountRequired { get { return whitelist.contains(entry.Activity__c); } }

Then in your markup, simply reference this flag property:

<apex:inputField value="{!entry.Account__c}" required="{!isAccountRequired}" />

This approach will scale well enough when adding more display logic, either new fields, new whitelists, or both.

If entry is an item in a collection, you have a couple options. The most straightforward is to use a wrapper class:

public class EntryWrapper
{
    public Boolean isAccountRequired { get; private set; }
    public MyObject__c record { get; private set; }
    public EntryWrapper(MyObject__c record)
    {
        this.record = record;
        this.isAccountRequired = whitelist.contains(record.Activity__c);
    }
}

Then your markup would change along the lines of:

<apex:repeat value="{!wrappers}" var="wrapper">
    <apex:inputField value="{!wrapper.record.Account__c}"
        required="{!wrapper.isAccountRequired}" />
</apex:repeat>