FormulaInstance Class
Contains a method to evaluate the formula instance.
Namespace
Example
1global class MotorYacht {
2 global Integer lengthInYards;
3 global Integer numOfGuestCabins;
4 global String name;
5 global Account owner;
6}1
2MotorYacht aBoat = new MotorYacht();
3aBoat.lengthInYards = 52;
4aBoat.numOfGuestCabins = 4;
5aBoat.name = 'RV Foo';
6FormulaEval.FormulaInstance isItSuper = Formula.builder()
7 .withReturnType(FormulaEval.FormulaReturnType.STRING)
8 .withType(MotorYacht.class)
9 .withFormula('IF(lengthInYards < 100, "Not Super", "Super")')
10 .build();
11isItSuper.evaluate(aBoat); //=> "Not Super"
12
13aBoat.owner = new Account(Name='Acme Watercraft', Site='New York');
14FormulaEval.FormulaInstance ownerDetails = Formula.builder()
15 .withReturnType(FormulaEval.FormulaReturnType.STRING)
16 .withType(MotorYacht.class)
17 .withFormula('owner.Name & " (" & owner.Site & ")"')
18 .build();
19ownerDetails.evaluate(aBoat); //=> "Acme Watercraft (New York)"
20Usage
The context type in the withType method must be a global, user-defined Apex class. Any fields or properties that the formula references must also be global.
FormulaInstance Methods
The following are methods for FormulaInstance.
evaluate(contextObject)
Calculates the formula expression and returns the formula output.
Signature
public Object evaluate(Object contextObject)
Parameters
- contextObject
- Type: Object
- An instance of the Apex class as generated with the FormulaBuilder.builder() method.
Return Value
Type: Object
Apex type that corresponds to the Apex class as configured by the withType() method in the FormulaBuilder class.
getReferencedFields()
Returns a set of strings that denote the field names referenced in a formula.
Signature
public Set<String> getReferencedFields()
Usage
A formula is built and evaluated in the context of the current namespace of the subscriber org. If you package a formula that references fields, the fields must be fully qualified with the namespace name.
Example
1FormulaEval.FormulaInstance ff = Formula.builder()
2 .withType(Schema.Account.class)
3 .withReturnType(FormulaEval.FormulaReturnType.STRING)
4 .withFormula('name & website')
5 .build();
6
7// Returns the field names 'name', and 'website' required to process the formula
8Set<String> fieldNames = ff.getReferencedFields();
9
10// Use the list of field names to generate dynamic soql
11String queryStr = 'select ' + string.join(fieldNames, ', ') + ' from Account limit 1';
12List<sObject> accounts = Database.query(queryStr);
13string formulaOutput = (string)ff.evaluate(accounts[0]);
14System.debug(formulaOutput);