Sub topic 6
Converting input to Id, Integer, Date and Boolean before use
This chapter assumes you can write Apex classes, run static SOQL, and use bind variables in Database.query. It covers what to do when the user's input is not text.
Why typed input matters
A bind variable protects a value from being read as query structure. The type of that value still matters. If you take a String from a page or an API call and place it in a query unchanged, you have two problems:
- The value may not be what you expect, such as
abcwhere a number belongs. - If you concatenate the value into the query instead of binding it, the string can change the query.
Converting input to a real type first fixes both. The conversion throws an exception for bad input, and a typed value cannot hold a quote character or an OR clause.
The flow looks like this.
Conversion methods
Each type has a built-in conversion. All of them throw an exception on invalid input, so wrap them and return a clear message.
| Target type | Conversion | Failure |
|---|---|---|
| `Id` | `Id.valueOf(s)` | `StringException` |
| `Integer` | `Integer.valueOf(s)` | `TypeException` |
| `Date` | `Date.valueOf(s)` (format `yyyy-MM-dd`) | `TypeException` |
| `Boolean` | `Boolean.valueOf(s)` | `NullPointerException` for null, otherwise `false` for anything not equal to `true` |
Two details cause most mistakes. Boolean.valueOf('yes') returns false without any error, so a typo silently changes the result. Also, Id.valueOf accepts a valid 15 or 18 character ID for any object, so it does not prove the ID belongs to the object you expect.
A worked example
This method accepts four string parameters, such as values from a REST request, and converts each one before binding.
public with sharing class OpportunityFilter {
public class InputException extends Exception {}
public static List<Opportunity> search(
String accountIdText, String minAmountText, String closeAfterText, String isWonText
) {
Id accountId;
Integer minAmount;
Date closeAfter;
Boolean isWon;
try {
accountId = Id.valueOf(accountIdText);
if (accountId.getSObjectType() != Account.SObjectType) {
throw new InputException('accountId must be an Account Id');
}
minAmount = Integer.valueOf(minAmountText);
closeAfter = Date.valueOf(closeAfterText);
} catch (InputException e) {
throw e;
} catch (Exception e) {
throw new InputException('Invalid filter value: ' + e.getTypeName());
}
if (isWonText == null || !(isWonText.equalsIgnoreCase('true') || isWonText.equalsIgnoreCase('false'))) {
throw new InputException('isWon must be true or false');
}
isWon = Boolean.valueOf(isWonText);
Map<String, Object> binds = new Map<String, Object>{
'accountId' => accountId,
'minAmount' => minAmount,
'closeAfter' => closeAfter,
'isWon' => isWon
};
return Database.queryWithBinds(
'SELECT Id, Name, Amount FROM Opportunity ' +
'WHERE AccountId = :accountId AND Amount >= :minAmount ' +
'AND CloseDate > :closeAfter AND IsWon = :isWon LIMIT 50',
binds,
AccessLevel.USER_MODE
);
}
}The code does three things worth noting:
- It checks the object type of the ID with
getSObjectType(), which closes the gap thatId.valueOfleaves open. - It rejects any Boolean text other than
trueorfalsebefore converting, soyesfails loudly. - It reports only the exception type name to the caller, not the raw message, which can echo the input back.
When you cannot bind
Sometimes a value must be written into the query text, for example in a query that you build with concatenation for a reason the bind map cannot handle. In that case, convert first and then insert the typed value's own string form, never the original input.
Integer limitValue = Integer.valueOf(limitText);
if (limitValue < 1 || limitValue > 200) {
limitValue = 50;
}
String soql = 'SELECT Id, Name FROM Account LIMIT ' + limitValue;
List<Account> accounts = Database.query(soql);limitValue is an Integer, so the concatenated text can only be digits. Range-check it as well, because a valid integer can still be harmful, such as a very large limit or a negative number.
Exercise
Exercise
A method receives String idText and runs Database.query('SELECT Id FROM Contact WHERE AccountId = \'' + idText + '\''). Rewrite the check so that only a valid Account Id can reach the query, and say which line makes the check complete. Which exception do you expect Id.valueOf('abc') to throw?
Show answer
Convert and verify the type, then bind the typed value: Id accId = Id.valueOf(idText); if (accId.getSObjectType() != Account.SObjectType) { throw new IllegalArgumentException('Not an Account Id'); } followed by Database.query('SELECT Id FROM Contact WHERE AccountId = :accId'). The getSObjectType() comparison completes the check, because Id.valueOf alone accepts an Id of any object. Id.valueOf('abc') throws a StringException.
Exercise
Why is Boolean.valueOf('yes') a risk when it feeds a filter, and how do you guard against it?
Show answer
It returns false without an error, so the filter silently returns the wrong rows. Check that the text equals true or false, ignoring case, and reject anything else before calling Boolean.valueOf.