Sub topic 1
Two Ways to Calculate Values Declaratively
Prerequisites
Assume you know Salesforce objects, fields, records, and lookup and master-detail relationships. You should also understand basic spreadsheet logic, such as IF.
Salesforce provides two common declarative calculation tools:
- A formula field calculates a read-only value from fields on the current record or related records when Salesforce reads it.
- A roll-up summary field aggregates child records, such as summing line items on a master record. It requires a master-detail relationship and recalculates when relevant child records change.
Formula Fields: Read-Only Values with a Return Type
When you create a formula field, choose its return type. Common types include Text, Number, Currency, Checkbox, Date, and Date/Time. The formula must return a compatible value.
For example, a Text formula can classify an Opportunity by Amount:
IF(BLANKVALUE(Amount, 0) > 100000, "Large",
IF(BLANKVALUE(Amount, 0) > 10000, "Medium", "Small"))The result cannot be edited directly. Change the source fields or formula instead.
Operators and Everyday Functions
Use arithmetic operators such as +, -, *, and /. Comparison operators include =, <>, >, <, >=, and <=.
Useful functions include:
| Function | Purpose |
|---|---|
| `BLANKVALUE(value, replacement)` | Replaces a blank value |
| `TEXT(value)` | Converts a value to text |
| `ISPICKVAL(field, "value")` | Tests a picklist value |
A formula can read a related record through relationship traversal:
Account.Owner.NameBranching with IF and CASE
IF evaluates a condition and chooses one of two results. CASE compares one value with several possible values:
CASE(StageName,
"Prospecting", 10,
"Qualification", 25,
"Closed Won", 100,
0)The final 0 is the default when no stage matches.
Handling Blanks and Avoiding Divide-by-Zero
Treat blank values deliberately. Use BLANKVALUE when a missing number should behave like zero. Guard division before performing it:
IF(Line_Item_Count__c = 0, 0,
Total_Amount__c / Line_Item_Count__c)Exercise
Which tool should calculate the total of child Invoice Line records on an Invoice master record?
Show answer
Use a roll-up summary field with the SUM type when the relationship is master-detail. Use a formula field for a value derived from fields already available through the record or its relationships.