Tuesday, January 18, 2011

Comparing Salesforce Record ID's in Visualforce

Strangely enough, the Visualforce comparison operator does not work when comparing a 15-digit record ID with an 18-digit one. The workaround I concocted is to use a very specific Boolean property in my controller extension to perform the comparison instead, since I really wanted to avoid using any kind of custom ID conversion code that may become invalid in future releases.

public Boolean isCitizenshipCountryUnitedStates {
get {
return stdCtrler.getRecord().get('Citizenship_Country__c') == unitedStatesCountryId;
}
}

The situation I have is that I want to compare the Country of Citizenship specified on an application record (for custom object Application) to see whether the applicant is a U.S. citizen. Country of Citizenship is a Lookup(Country) field, with Country also being a custom object.

Without hardcoding the Id for the United States country, I defined a unitedStatesCountryId property as follows:

 public Id unitedStatesCountryId {
get {
if (unitedStatesCountryId == null) {
List matchingCountries =
[SELECT Id FROM Country__c
WHERE Name = 'United States'];

if (matchingCountries.size() > 0) {
unitedStatesCountryId = matchingCountries.get(0).Id;
}
}

return unitedStatesCountryId;
}

set;
}

When I evaluate the expression {!Application__c.Citizenship_Country__c = unitedStatesCountryId} in my Visualforce page, the expression always returns false. When digging a little deeper, I found that Application__c.Citizenship_Country__c was returning 'a0DT0000006NIDM' while unitedStatesCountryId was returning 'a0DT0000006NIDMMA4'! Visualforce appeared to be comparing the two values as Strings and not as Ids.

Finding no Visualforce-native solution, I had to go the route of creating the isCitizenshipCountryUnitedStates property in my controller extension. Needless to say, this quirk in Salesforce does not make me happy.