Understanding Functions
Functions are expressions that accept inputs (called arguments), perform operations or evaluations, and return calculated results. Functions enable administrators to implement business logic, perform calculations, manipulate text, compare values, evaluate conditions, and control system behavior without programming. Think of functions as tools that do specific jobs: some check if values are equal, some combine text, some calculate dates, and some make decisions based on conditions.
This guide explains function syntax, categories, and usage patterns, and provides a complete reference of all available functions with examples to help administrators build sophisticated formulas for validation rules, email templates, page layouts, buttons, automations, and other platform features.
What Are Functions?
Functions are similar to formulas in spreadsheet applications like Excel or Google Sheets. If you've ever written =SUM(A1:A10) or =IF(B1>100,"High","Low") in a spreadsheet, you already understand the basic concept of functions.
A function has three components:
- Function Name: Identifies which operation to perform (e.g.,
Equal, IsNull, Concat) - Arguments: The inputs the function needs to perform its operation (values, merge fields, or other functions)
- Return Value: The result the function produces after processing its arguments
Example:{!Equal(Status,"Active")}
- Function Name:
Equal - Arguments:
Status and "Active" - Return Value:
True if Status equals "Active", otherwise False
Function Syntax
Basic Structure
Functions follow this format:
{!FunctionName(argument1,argument2,argument3)}
Components:
- Curly braces with exclamation:
{! opens the function - Function name: Identifies the function
- Parentheses:
() contain the arguments, even if there are no arguments - Arguments: Separated by commas with no spaces
- Closing brace:
} closes the function
Syntax Rules
- Functions always include parentheses, even when they accept no arguments:
{!Today()} - Arguments are separated by commas with no spaces:
arg1,arg2,arg3 - Text strings must be enclosed in double quotation marks:
"Active" - Function names are case-sensitive:
Equal not equal - Functions can be nested:
{!If(IsNull(Email), "No Email", "Has Email")} - Merge fields can be arguments:
{!IsNull(Contact.Email)}
Arguments
Functions accept different types of arguments:
Merge Fields:
{!IsNull(Email)} - Merge field as argument
{!Equal(Status, "Closed Won")} - Merge field compared to text
Text Strings:
{!Concat("Hello", " ", "World")} - Multiple text strings
Text strings must be enclosed in double quotes.
Numbers:
{!MoreThan(Amount,1000)} - Number as argument
{!AddDateTimePart($Today,"days",30)} - Number specifying quantity
Other Functions:
{!If(IsNull(Email),"No Email",Email)} - Function as argument
Functions can be nested inside other functions.
Boolean Values:
{!IsActive} - Direct use of checkbox field (returns True or False)
{!Equal(IsActive,true)} - Comparing boolean to True (unnecessary, direct use is better)
Boolean fields can be used directly in conditions without comparison functions.
Return Values
Functions return different types of values:
- Boolean (True/False): Logical and comparison functions return True or False
- Text: Text functions and conditional functions can return text strings
- Numbers: Mathematical functions return numeric values
- Dates/Times: Date functions return date or datetime values
Function Categories
Functions are organized into categories based on their purpose. Understanding categories helps you find the right function for your needs.
Logical Functions
Logical functions evaluate conditions and return True or False, or make decisions based on conditions.
Examples:IsNull(), HasValue(), Equal(), If(), AND(), OR(), Not()
Comparison Functions
Comparison functions compare two values and return True or False.
Examples:Equal(), NotEqual(), LessThan(), MoreThan(), LessThanOrEqual(), MoreThanOrEqual()
Text Functions
Text functions manipulate, combine, or analyze text strings.
Examples:Concat(), ToUpper(), ToLower(), Len(), Contains(), Replace(), StartsWith(), Text()
Date and Time Functions
Date and time functions work with dates, times, and date arithmetic.
Examples:Today(), AddDateTimePart(), AddDays(), ToUserTime(), FormatDate(), FormatDateTime()
Mathematical Functions
Mathematical functions perform arithmetic operations.
Examples:Add(), FormatNumber(), FormatCurrency()
System and URL Functions
System and URL functions generate URLs, encode values, and access system information.
Examples:ActivePageUrl(), UrlFor(), GetSiteUrl(), UrlEncode(), UrlDecode(), IsInRole()
Utility Functions
Utility functions provide specialized capabilities like GUID generation, address formatting, and encryption.
Examples:NewGuid(), FormatAddress(), Encrypt(), EscapeSingleQuote()
Complete Function Reference
The following table provides a quick reference for all available functions. Detailed explanations and examples for each function follow the table.
| Function | Return Type | Description |
|---|
| Logical Functions |
IsNull(expression) | Boolean | Returns True if expression is null (empty/blank) |
HasValue(expression) | Boolean | Returns True if expression has a value (not null) |
IsBlank(expression) | Boolean | Returns True if expression is blank (null, empty string, or whitespace only) |
NullValue(expression,substitute) | Any | Returns expression if not blank, otherwise returns substitute value |
If(expression,trueValue,falseValue) | Any | Returns trueValue if expression is True, otherwise returns falseValue |
AND(expression1,expression2,...) | Boolean | Returns True if ALL expressions are True (accepts unlimited arguments) |
OR(expression1,expression2,...) | Boolean | Returns True if ANY expression is True (accepts unlimited arguments) |
Not(expression) | Boolean | Returns the opposite boolean value (True becomes False, False becomes True) |
| Comparison Functions |
Equal(value1,value2) | Boolean | Returns True if value1 equals value2 |
NotEqual(value1,value2) | Boolean | Returns True if value1 does not equal value2 |
LessThan(value1,value2) | Boolean | Returns True if value1 is less than value2 |
LessThanOrEqual(value1,value2) | Boolean | Returns True if value1 is less than or equal to value2 |
MoreThan(value1,value2) | Boolean | Returns True if value1 is greater than value2 |
MoreThanOrEqual(value1,value2) | Boolean | Returns True if value1 is greater than or equal to value2 |
| Text Functions |
Text(expression) | Text | Converts expression to text string |
Concat(string1,string2,...) | Text | Combines multiple text strings into one (accepts unlimited arguments) |
ToUpper(text) | Text | Converts text to all uppercase letters |
ToLower(text) | Text | Converts text to all lowercase letters |
Len(text) | Number | Returns the number of characters in text string |
Contains(text,searchValue) | Boolean | Returns True if text contains searchValue (case-sensitive) |
StartsWith(text,prefix) | Boolean | Returns True if text starts with prefix (case-sensitive) |
Replace(text,pattern,replacement,ignoreCase) | Text | Replaces all occurrences of pattern with replacement in text |
EscapeSingleQuote(text) | Text | Escapes single quotes in text by adding backslash |
| Date and Time Functions |
Today() | Date | Returns current date (UTC) at midnight |
AddDateTimePart(datetime,part,value) | DateTime | Adds value to specified datetime part (years, months, days, hours, minutes, seconds, ticks) |
AddDays(date,days) | Date | Adds specified number of days to date |
ToUserTime(datetime) | DateTime | Converts datetime from UTC to user's configured timezone |
FormatDate(datetime) | Text | Formats datetime as date string per user's locale |
FormatDateTime(datetime) | Text | Formats datetime as date and time string per user's locale |
| Mathematical Functions |
Add(number1,number2,...) | Number | Adds multiple numbers together (accepts unlimited arguments) |
FormatNumber(value,decimalPlaces) | Text | Formats numeric value with specified decimal places |
FormatCurrency(value,currencyCode,decimalPlaces) | Text | Formats numeric value as currency with currency code and decimal places |
| System and URL Functions |
IsInRole(roleName) | Boolean | Returns True if current user is assigned the specified security role |
ActivePageUrl(pageName) | Text | Returns URL for specified Active Page |
ActivePageUrl(pageName,routeValues) | Text | Returns URL for specified Active Page with route parameters |
UrlFor(action,controller,routeValues) | Text | Generates URL for specific controller action with route parameters |
GetSiteUrl() | Text | Returns base URL of current Magentrix site |
PageUrl() | Text | Returns URL of current page |
UrlEncode(value) | Text | Encodes string for safe use in URLs |
UrlDecode(value) | Text | Decodes URL-encoded string back to normal text |
UrlParam(parameterName) | Text | Retrieves value of URL query string parameter |
UrlTokenEncode(value) | Text | Encodes value as URL-safe token for secure parameter passing |
UrlForAsset(relativePath) | Text | Returns URL for static asset file |
GetAppName() | Text | Returns name of current app context |
| Utility Functions |
NewGuid() | Text | Generates new globally unique identifier (GUID) |
FormatAddress(street,city,state,postalCode,country) | Text | Formats address components into properly formatted mailing address |
Encrypt(value,base64Encoding) | Text | Encrypts value for secure transmission with base64 encoding option |
Encrypt(value,token) | Text | Encrypts value using encryption token |
Logical Functions
IsNull
Syntax:{!IsNull(expression)}
Description: Returns True if the expression is null (empty/blank), otherwise returns False.
Arguments:
expression - The field or value to check
Returns: Boolean (True or False)
Examples:
{!IsNull(Email)} - Returns True if Email field is empty{!IsNull(Account.Phone)} - Returns True if Account Phone is empty{!IsNull(CustomField__c)} - Returns True if custom field is empty
Common Use: Validation rules requiring fields be populated, conditional visibility based on whether fields have values.
HasValue
Syntax:{!HasValue(expression)}
Description: Returns True if the expression has a value (is not null), otherwise returns False. This is the opposite of IsNull.
Arguments:
expression - The field or value to check
Returns: Boolean (True or False)
Examples:
{!HasValue(PhoneNumber)} - Returns True if PhoneNumber field has a value{!HasValue(Account.BillingStreet)} - Returns True if billing address exists
Common Use: Validation rules ensuring fields are populated, showing sections only when data exists.
IsBlank
Syntax:{!IsBlank(expression)}
Description: Returns True if the expression is blank (null, empty string, or whitespace only), otherwise returns False. Similar to IsNull but also treats whitespace-only strings as blank.
Arguments:
expression - The field or value to check
Returns: Boolean (True or False)
Examples:
{!IsBlank(Description)} - Returns True if Description is empty or contains only spaces
Common Use: More thorough validation than IsNull, catching fields that contain only whitespace.
NullValue
Syntax:{!NullValue(expression,substitute)}
Description: Returns the expression if it is not blank, otherwise returns the substitute value. This function allows you to provide a default value when a field is empty.
Arguments:
expression - The field or value to checksubstitute - The value to return if expression is null
Returns: The expression value or the substitute value
Examples:
{!NullValue(PhoneNumber,"Not Provided")} - Returns phone number or "Not Provided" if empty{!NullValue(Account.Name,"No Account")} - Returns account name or "No Account" if empty{!NullValue(Email,"no-email@domain.com")} - Returns email or placeholder if empty
Common Use: Email templates providing default text when fields are empty, formulas requiring non-null values.
If
Syntax:{!If(expression,trueValue,falseValue)}
Description: Evaluates the expression and returns trueValue if the expression is True, otherwise returns falseValue. This is the primary function for conditional logic.
Arguments:
expression - The condition to evaluate (must return True or False)trueValue - The value to return if expression is TruefalseValue - The value to return if expression is False
Returns: trueValue or falseValue depending on the expression
Examples:
{!If(Equal(Status,"Active"),"Enabled","Disabled")} - Returns "Enabled" or "Disabled"{!If(MoreThan(Amount,1000),"High Value","Standard")} - Categorizes amounts{!If(IsNull(Email),"No Email Provided",Email)} - Shows email or message{!If(IsInRole("Administrator"),ActivePageUrl("AdminPage"),ActivePageUrl("UserPage"))} - Different pages for different roles
Common Use: Conditional content in emails, dynamic button URLs, field visibility logic, validation rule messages.
AND
Syntax:{!AND(expression1,expression2,expression3,...)}
Description: Returns True if ALL expressions are True, otherwise returns False. This function accepts unlimited number of arguments.
Arguments:
expression1, expression2, ... - Any number of expressions that evaluate to True or False
Returns: Boolean (True or False)
Examples:
{!AND(Equal(Status,"Active"),HasValue(Email))} - True if Status is Active AND Email exists{!AND(MoreThan(Amount,1000),Equal(Stage,"Closed Won"))} - True if both conditions met{!AND(IsNull(Phone),IsNull(Email),IsNull(Website))} - True if all three fields empty{!AND(Equal(Type,"Customer"),HasValue(AccountNumber),MoreThan(AnnualRevenue,100000))} - Multiple conditions
Common Use: Validation rules requiring multiple conditions be met, complex visibility logic, multi-criteria filtering.
OR
Syntax:{!OR(expression1,expression2,expression3,...)}
Description: Returns True if ANY expression is True, otherwise returns False if all expressions are False. This function accepts unlimited number of arguments.
Arguments:
expression1, expression2, ... - Any number of expressions that evaluate to True or False
Returns: Boolean (True or False)
Examples:
{!OR(Equal(Status,"Pending"),Equal(Status,"In Review"))} - True if either status{!OR(IsNull(Email),IsNull(Phone))} - True if either field is empty{!OR(Equal(Priority,"High"),Equal(Priority,"Urgent"),Equal(Priority,"Critical"))} - True if any priority
Common Use: Validation rules where multiple acceptable conditions exist, visibility based on multiple possible values.
Not
Syntax:{!Not(expression)}
Description: Returns the opposite boolean value. True becomes False, False becomes True.
Arguments:
expression - The boolean value to reverse
Returns: Boolean (True or False)
Examples:
{!Not(Equal(Status,"Closed"))} - True if Status is NOT "Closed"{!Not(IsNull(Email))} - True if Email is NOT empty (same as HasValue){!Not(IsInRole("Administrator"))} - True if user is NOT an administrator
Common Use: Negating conditions, validation rules preventing certain states, inverse visibility logic.
Comparison Functions
Equal
Syntax:{!Equal(value1,value2)}
Description: Returns True if value1 and value2 are equal, otherwise returns False.
Arguments:
value1 - First value to comparevalue2 - Second value to compare
Returns: Boolean (True or False)
Examples:
{!Equal(Status,"Active")} - True if Status equals "Active"{!Equal(Amount,1000)} - True if Amount equals 1000{!Equal(Account.Type,"Customer")} - True if Account Type is "Customer"
Common Use: Validation rules checking specific values, visibility based on field values, conditional logic.
NotEqual
Syntax:{!NotEqual(value1,value2)}
Description: Returns True if value1 and value2 are NOT equal, otherwise returns False.
Arguments:
value1 - First value to comparevalue2 - Second value to compare
Returns: Boolean (True or False)
Examples:
{!NotEqual(Status,"Closed")} - True if Status is not "Closed"{!NotEqual(Priority,"Low")} - True if Priority is not "Low"
Common Use: Validation rules preventing specific values, excluding certain conditions.
LessThan
Syntax:{!LessThan(value1,value2)}
Description: Returns True if value1 is less than value2, otherwise returns False.
Arguments:
value1 - First value to comparevalue2 - Second value to compare
Returns: Boolean (True or False)
Examples:
{!LessThan(Amount,1000)} - True if Amount is less than 1000{!LessThan(Quantity,100)} - True if Quantity is less than 100{!LessThan(CloseDate,$Today)} - True if CloseDate is in the past
Common Use: Validation rules enforcing minimum values, date comparisons, numeric range validation.
LessThanOrEqual
Syntax:{!LessThanOrEqual(value1,value2)}
Description: Returns True if value1 is less than or equal to value2, otherwise returns False.
Arguments:
value1 - First value to comparevalue2 - Second value to compare
Returns: Boolean (True or False)
Examples:
{!LessThanOrEqual(Discount,25)} - True if Discount is 25 or less{!LessThanOrEqual(Age,18)} - True if Age is 18 or under
Common Use: Validation rules with inclusive maximum limits, eligibility checks.
MoreThan
Syntax:{!MoreThan(value1,value2)}
Description: Returns True if value1 is greater than value2, otherwise returns False.
Arguments:
value1 - First value to comparevalue2 - Second value to compare
Returns: Boolean (True or False)
Examples:
{!MoreThan(Amount,5000)} - True if Amount exceeds 5000{!MoreThan(Score,90)} - True if Score is above 90{!MoreThan(DaysOverdue,30)} - True if more than 30 days overdue
Common Use: Validation rules enforcing maximum values, threshold detection, escalation logic.
MoreThanOrEqual
Syntax:{!MoreThanOrEqual(value1,value2)}
Description: Returns True if value1 is greater than or equal to value2, otherwise returns False.
Arguments:
value1 - First value to comparevalue2 - Second value to compare
Returns: Boolean (True or False)
Examples:
{!MoreThanOrEqual(Age,21)} - True if Age is 21 or older{!MoreThanOrEqual(GPA,3.5)} - True if GPA is 3.5 or higher
Common Use: Validation rules with inclusive minimum requirements, qualification criteria.
Text Functions
Text
Syntax:{!Text(expression)}
Description: Converts the expression to a text string. Useful for converting numbers or dates to text for concatenation or comparison.
Arguments:
expression - The value to convert to text
Returns: Text string
Examples:
{!Text(Amount)} - Converts numeric Amount to text{!Concat("Total: ",Text(Amount))} - Combine text with number
Common Use: Converting values for text operations, building composite text strings with mixed data types.
Concat
Syntax:{!Concat(string1,string2,string3,...)}
Description: Combines multiple text strings into a single string. Accepts any number of arguments.
Arguments:
string1, string2, ... - Text strings to combine
Returns: Text string
Examples:
{!Concat(Firstname," ",Lastname)} - Combines first and last name with space{!Concat("Welcome to ",Account.Name,"!")} - Creates greeting with account name{!Concat(BillingStreet,", ",BillingCity,", ",BillingState," ",BillingPostalCode)} - Formats full address
Common Use: Email templates creating personalized greetings, formula fields combining multiple values, formatted output.
ToUpper
Syntax:{!ToUpper(text)}
Description: Converts text string to all uppercase letters.
Arguments:
text - The text string to convert
Returns: Text string in uppercase
Examples:
{!ToUpper(Name)} - Converts "John Smith" to "JOHN SMITH"{!ToUpper(ProductCode)} - Converts "abc123" to "ABC123"
Common Use: Standardizing text format, display formatting, case-insensitive comparisons.
ToLower
Syntax:{!ToLower(text)}
Description: Converts text string to all lowercase letters.
Arguments:
text - The text string to convert
Returns: Text string in lowercase
Examples:
{!ToLower(Email)} - Converts "USER@DOMAIN.COM" to "user@domain.com"{!ToLower(Status)} - Converts "ACTIVE" to "active"
Common Use: Email address normalization, case-insensitive comparisons, formatting.
Len
Syntax:{!Len(text)}
Description: Returns the number of characters in the text string.
Arguments:
text - The text string to measure
Returns: Number (integer)
Examples:
{!Len(Description)} - Returns character count of Description{!MoreThan(Len(Description),100)} - True if description exceeds 100 characters{!LessThan(Len(Username),5)} - True if username is less than 5 characters
Common Use: Validation rules enforcing minimum/maximum text length, character count limits.
Contains
Syntax:{!Contains(text,searchValue)}
Description: Returns True if text contains searchValue, otherwise returns False. Case-sensitive.
Arguments:
text - The text string to search withinsearchValue - The text to search for
Returns: Boolean (True or False)
Examples:
{!Contains(Description,"urgent")} - True if Description contains "urgent"{!Contains(Email,"@gmail.com")} - True if Email is Gmail address{!Contains(ProductName,"Enterprise")} - True if product name includes "Enterprise"
Common Use: Text pattern validation, keyword detection, filtering based on text content.
StartsWith
Syntax:{!StartsWith(text,prefix)}
Description: Returns True if text starts with the specified prefix, otherwise returns False. Case-sensitive.
Arguments:
text - The text string to checkprefix - The prefix to look for
Returns: Boolean (True or False)
Examples:
{!StartsWith(AccountNumber,"ENT")} - True if account number starts with "ENT"{!StartsWith(ProductCode,"PRO")} - True if product code starts with "PRO"
Common Use: Pattern validation, categorization based on prefixes, code structure validation.
Replace
Syntax:{!Replace(text,pattern,replacement,ignoreCase)}
Description: Replaces all occurrences of pattern in text with replacement.
Arguments:
text - The text string to modifypattern - The text to find and replacereplacement - The text to substituteignoreCase - True for case-insensitive, False for case-sensitive
Returns: Modified text string
Examples:
{!Replace(PhoneNumber,"-","","false")} - Removes dashes from phone number{!Replace(Description,"old","new","true")} - Replaces "old" with "new" (case-insensitive)
Common Use: Text formatting, standardization, character removal or substitution.
EscapeSingleQuote
Syntax:{!EscapeSingleQuote(text)}
Description: Escapes single quotes in text by adding backslash, preventing syntax errors in JavaScript or other contexts.
Arguments:
text - The text string to escape
Returns: Text string with escaped quotes
Examples:
{!EscapeSingleQuote(Description)} - Converts "It's great" to "It\'s great"
Common Use: Preparing text for JavaScript contexts, preventing syntax errors in dynamic code.
Date and Time Functions
Today
Syntax:{!Today()}
Description: Returns the current date (UTC) at midnight (12:00 AM). No arguments required.
Arguments: None
Returns: Date value
Examples:
{!Today()} - Current date{!LessThan(ExpirationDate,Today())} - True if expiration date is past{!MoreThan(StartDate,Today())} - True if start date is future
Common Use: Date comparisons, age calculations, expiration checking, date validation.
Note: Also available as global merge field {!$Today}
AddDateTimePart
Syntax:{!AddDateTimePart(datetime,part,value)}
Description: Adds or subtracts a specified value to a date/time component and returns the result.
Arguments:
datetime - The date or datetime to modifypart - The component to modify: "years", "months", "days", "hours", "minutes", "seconds", or "ticks"value - The numeric amount to add (positive) or subtract (negative)
Returns: Modified date/datetime value
Examples:
{!AddDateTimePart($Today,"days",30)} - 30 days from today{!AddDateTimePart($Today,"days",-7)} - 7 days ago{!AddDateTimePart(StartDate,"months",3)} - 3 months after start date{!AddDateTimePart(RenewalDate,"years",1)} - 1 year after renewal date{!AddDateTimePart($Now,"hours",2)} - 2 hours from now
Common Use: Calculating future dates, determining past dates, date arithmetic in formulas, deadline calculations.
AddDays
Syntax:{!AddDays(date,days)}
Description: Adds the specified number of days to a date and returns the result. Simplified version of AddDateTimePart for days only.
Arguments:
date - The date to modifydays - The number of days to add (can be negative to subtract)
Returns: Modified date value
Examples:
{!AddDays($Today,15)} - 15 days from today{!AddDays(OrderDate,30)} - 30 days after order date{!AddDays($Today,-5)} - 5 days ago
Common Use: Payment terms calculations, delivery date estimates, deadline calculations.
ToUserTime
Syntax:{!ToUserTime(datetime)}
Description: Converts a datetime value from UTC to the current user's configured timezone.
Arguments:
datetime - The datetime value to convert (typically in UTC)
Returns: Datetime value in user's timezone
Examples:
{!ToUserTime(CreatedDate)} - Converts record creation time to user timezone{!ToUserTime($Now)} - Current time in user timezone
Common Use: Displaying dates/times to users in their local timezone, email templates with localized times.
FormatDate
Syntax:{!FormatDate(datetime)}
Description: Formats a datetime value as a date string according to the user's locale settings.
Arguments:
datetime - The datetime value to format
Returns: Formatted date string
Examples:
{!FormatDate($Today)} - Formats today's date{!FormatDate(CloseDate)} - Formats close date as readable string
Common Use: Email templates displaying dates, reports with formatted dates, user-friendly date display.
FormatDateTime
Syntax:{!FormatDateTime(datetime)}
Description: Formats a datetime value as a date and time string according to the user's locale settings.
Arguments:
datetime - The datetime value to format
Returns: Formatted datetime string
Examples:
{!FormatDateTime($Now)} - Formats current date and time{!FormatDateTime(CreatedDate)} - Formats creation timestamp
Common Use: Email templates showing timestamps, activity logs, time-sensitive communications.
Mathematical Functions
Add
Syntax:{!Add(number1,number2,number3,...)}
Description: Adds multiple numbers together and returns the sum. Accepts any number of arguments.
Arguments:
number1, number2, ... - Numbers to add together
Returns: Numeric sum
Examples:
{!Add(Amount1,Amount2,Amount3)} - Sums three amounts{!Add(Subtotal,Tax,Shipping)} - Calculates total with tax and shipping
Common Use: Formula fields calculating totals, summing multiple values, financial calculations.
FormatNumber
Syntax:{!FormatNumber(value,decimalPlaces)}
Description: Formats a numeric value with specified decimal places.
Arguments:
value - The number to formatdecimalPlaces - Number of decimal places to display
Returns: Formatted number string
Examples:
{!FormatNumber(Total,2)} - Formats to 2 decimal places (e.g., "123.45"){!FormatNumber(Percentage,1)} - Formats to 1 decimal place (e.g., "95.5")
Common Use: Email templates displaying formatted numbers, consistent numeric display, financial reporting.
FormatCurrency
Syntax:{!FormatCurrency(value,currencyCode,decimalPlaces)}
Description: Formats a numeric value as currency with specified currency code and decimal places.
Arguments:
value - The number to formatcurrencyCode - Currency code (e.g., "USD", "EUR", "GBP")decimalPlaces - Number of decimal places to display
Returns: Formatted currency string
Examples:
{!FormatCurrency(Amount,"USD",2)} - Formats as "$1,234.56"{!FormatCurrency(Total,"EUR",2)} - Formats as "€1.234,56"{!FormatCurrency(Price,"GBP",0)} - Formats as "£1,235"
Common Use: Email templates with pricing, invoices, financial reports, quotes and proposals.
System and URL Functions
IsInRole
Syntax:{!IsInRole(roleName)}
Description: Returns True if the current user is assigned the specified security role, otherwise returns False.
Arguments:
roleName - The exact name of the security role (case-sensitive)
Returns: Boolean (True or False)
Examples:
{!IsInRole("Administrator")} - True if user is Administrator{!IsInRole("Partner Portal User")} - True if user has Partner Portal User role{!IsInRole("Sales Manager")} - True if user is Sales Manager
Common Use: Page layout visibility based on role, conditional buttons, role-specific email content, security filtering.
ActivePageUrl
Syntax:{!ActivePageUrl(pageName)} or {!ActivePageUrl(pageName,routeValues)}
Description: Returns the URL for a specified Active Page, optionally with route parameters.
Arguments:
pageName - The name of the Active PagerouteValues - Optional route parameters object
Returns: URL string
Examples:
{!ActivePageUrl("CustomerDashboard")} - URL to Customer Dashboard page{!ActivePageUrl("ProductDetail")} - URL to Product Detail page{!$Organization.OrgURL}/{!ActivePageUrl("Portal")} - Full URL to portal page
Common Use: Email templates with links to portal pages, custom buttons navigating to pages, dynamic navigation.
UrlFor
Syntax:{!UrlFor(action,controller,routeValues)}
Description: Generates a URL for a specific controller action with optional route parameters.
Arguments:
action - The action namecontroller - The controller namerouteValues - Optional route parameters
Returns: URL string
Examples:
{!UrlFor("Details","Account")} - URL to Account details action
Common Use: Custom buttons with specific controller actions, dynamic navigation to system pages.
GetSiteUrl
Syntax:{!GetSiteUrl()}
Description: Returns the base URL of the current Magentrix site.
Arguments: None
Returns: URL string
Examples:
{!GetSiteUrl()} - Returns "https://yourcompany.magentrix.com"{!Concat(GetSiteUrl(),"/custom-page")} - Builds full URL
Common Use: Building full URLs, external integrations, email templates with portal links.
PageUrl
Syntax:{!PageUrl()}
Description: Returns the URL of the current page.
Arguments: None
Returns: URL string
Common Use: Capturing current page context, breadcrumb building, referral tracking.
UrlEncode
Syntax:{!UrlEncode(value)}
Description: Encodes a string for use in a URL, converting special characters to URL-safe format.
Arguments:
value - The string to encode
Returns: URL-encoded string
Examples:
{!UrlEncode(Account.Name)} - Encodes "Smith & Associates" to "Smith%20%26%20Associates"{!UrlEncode(SearchQuery)} - Encodes search terms for URL
Common Use: Building URLs with dynamic parameters, passing data in query strings, external integrations.
UrlDecode
Syntax:{!UrlDecode(value)}
Description: Decodes a URL-encoded string back to normal text.
Arguments:
value - The URL-encoded string to decode
Returns: Decoded text string
Common Use: Processing URL parameters, decoding query strings, displaying URL-encoded values.
UrlParam
Syntax:{!UrlParam(parameterName)}
Description: Retrieves the value of a URL query string parameter.
Arguments:
parameterName - The name of the URL parameter to retrieve
Returns: Parameter value string
Examples:
{!UrlParam("id")} - Gets "id" parameter from URL{!UrlParam("source")} - Gets "source" parameter from URL
Common Use: Capturing campaign parameters, tracking sources, dynamic page content based on URL parameters.
UrlTokenEncode
Syntax:{!UrlTokenEncode(value)}
Description: Encodes a value as a URL-safe token for secure parameter passing.
Arguments:
value - The value to encode as token
Returns: URL token string
Common Use: Secure parameter passing, token-based authentication, encrypted URL parameters.
UrlForAsset
Syntax:{!UrlForAsset(relativePath)}
Description: Returns the URL for a static asset file.
Arguments:
relativePath - The relative path to the asset
Returns: Asset URL string
Common Use: Referencing images, CSS files, JavaScript files in email templates or pages.
GetAppName
Syntax:{!GetAppName()}
Description: Returns the name of the current app context.
Arguments: None
Returns: App name string
Common Use: Conditional logic based on app context, app-specific branding or content.
Utility Functions
NewGuid
Syntax:{!NewGuid()}
Description: Generates a new globally unique identifier (GUID).
Arguments: None
Returns: GUID string (e.g., "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6")
Common Use: Generating unique identifiers, tracking tokens, unique record keys.
FormatAddress
Syntax:{!FormatAddress(street,city,state,postalCode,country)}
Description: Formats address components into a properly formatted mailing address string.
Arguments:
street - Street addresscity - City namestate - State or provincepostalCode - ZIP or postal codecountry - Country name
Returns: Formatted address string
Examples:
{!FormatAddress(BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry)} - Formats billing address{!FormatAddress(ShippingStreet,ShippingCity,ShippingState,ShippingPostalCode,ShippingCountry)} - Formats shipping address
Common Use: Email templates with formatted addresses, mailing labels, invoice generation.
Encrypt
Syntax:{!Encrypt(value,base64Encoding)} or {!Encrypt(value,token)}
Description: Encrypts a value for secure transmission or storage.
Arguments:
value - The value to encryptbase64Encoding - Boolean indicating if result should be base64 encodedtoken - Encryption token
Returns: Encrypted string
Common Use: Secure parameter passing, protecting sensitive data in URLs, token generation.
Combining Functions with Merge Fields
The real power of functions comes from combining them with merge fields to create dynamic, intelligent formulas. Merge fields provide the data, and functions process that data to produce results.
Basic Combinations
Testing if a Field is Empty:
{!IsNull(Email)}
Merge field Email is the argument to function IsNull()
Comparing a Field to a Value:
{!Equal(Status,"Active")}
Merge field Status compared to text string "Active"
Checking if a Number Exceeds a Threshold:
{!MoreThan(Amount,5000)}
Merge field Amount compared to number 5000
Relationship Navigation in Functions
Testing Related Entity Fields:
{!IsNull(Account.Phone)}
Function tests if related Account's Phone is empty
Comparing Related Entity Values:
{!Equal(Account.Type,"Customer")}
Function compares related Account's Type
Multi-Level Navigation:
{!Equal(Account.Owner.Name,"John Smith")}
Function compares Account Owner's Name
Global System Merge Fields in Functions
Comparing to Current User:
{!Equal(OwnerId,$User.Id)}
Tests if record owner is current user
Date Calculations with Today:
{!LessThan(ExpirationDate,$Today)}
Tests if expiration is in past
Adding Days to Today:
{!AddDateTimePart($Today,"days",30)}
Calculates date 30 days from today
Nesting Functions
Functions can be nested inside other functions, where one function's result becomes another function's argument. This enables complex logic in a single formula.
Simple Nesting
Checking if Email is Empty, Then Providing Default:
{!If(IsNull(Email),"No Email Provided",Email)}
Breakdown:
- Inner function:
IsNull(Email) returns True or False - Outer function:
If() uses that result to decide what to return - If True: Returns "No Email Provided"
- If False: Returns the Email value
Multiple Levels of Nesting
Complex Conditional Logic:
{!If(IsNull(PrimaryEmail),If(IsNull(SecondaryEmail),"No Email","Use Secondary"),"Use Primary")}
Breakdown:
- First check: Is PrimaryEmail empty?
- If empty: Check if SecondaryEmail is empty
- If both empty: Return "No Email"
- If only Secondary exists: Return "Use Secondary"
- If Primary exists: Return "Use Primary"
Function Composition Patterns
Reversing Comparison Results:
{!Not(Equal(Status,"Closed"))}
True when Status is NOT "Closed"
Combining Multiple Conditions:
{!AND(HasValue(Email),HasValue(Phone))}
True when both Email and Phone have values
Any of Several Conditions:
{!OR(Equal(Priority,"High"),Equal(Priority,"Urgent"),Equal(Priority,"Critical"))}
True when Priority is any of the three values
Complex Validation:
{!AND(Equal(Stage,"Closed Won"),OR(IsNull(CloseDate),IsNull(Amount)))}
True when Stage is "Closed Won" AND either CloseDate or Amount is empty
Common Formula Patterns
Required Field When Condition Met
Use Case: Require Lost Reason when Opportunity Stage is "Closed Lost"
Formula:
{!AND(Equal(Stage,"Closed Lost"),IsNull(LostReason))}
Logic: Returns True (error) when Stage is "Closed Lost" AND LostReason is empty
Mutually Exclusive Fields
Use Case: Either Email or Phone must be provided, but not required to have both
Formula:
{!AND(IsNull(Email),IsNull(Phone))}
Logic: Returns True (error) when BOTH fields are empty
Date Range Validation
Use Case: End Date must be after Start Date
Formula:
{!AND(HasValue(EndDate),LessThan(EndDate,StartDate))}
Logic: Returns True (error) when End Date exists and is before Start Date
Conditional Required Field
Use Case: If Country is "USA", State must be provided
Formula:
{!AND(Equal(Country,"USA"),IsNull(State))}
Logic: Returns True (error) when Country is "USA" AND State is empty
Numeric Range Validation
Use Case: Discount cannot exceed 25%
Formula:
{!MoreThan(Discount,25)}
Logic: Returns True (error) when Discount exceeds 25
Text Length Validation
Use Case: Description must be at least 50 characters
Formula:
{!AND(HasValue(Description),LessThan(Len(Description),50))}
Logic: Returns True (error) when Description exists but is less than 50 characters
Role-Based Visibility
Use Case: Show section only to Administrators
Formula:
{!IsInRole("Administrator")}
Logic: Returns True (visible) when user is Administrator
Conditional Email Content
Use Case: Different greeting based on account type
Formula:
{!If(Equal(Account.Type,"Partner"),"Dear Partner","Dear Customer")}
Logic: Returns appropriate greeting based on account type
Dynamic Button URL
Use Case: Button directs to different pages based on user role
Formula:
{!If(IsInRole("Administrator"),ActivePageUrl("AdminDashboard"),ActivePageUrl("UserDashboard"))}
Logic: Returns appropriate page URL based on role
Progressive Examples: Simple to Complex
Level 1: Simple Single Function
Scenario: Check if Email is empty
Formula:{!IsNull(Email)}
Result: True if empty, False if has value
Level 2: Function with Comparison
Scenario: Check if Status is "Active"
Formula:{!Equal(Status,"Active")}
Result: True if Status equals "Active", False otherwise
Level 3: Simple AND Logic
Scenario: Both Email and Phone must have values
Formula:{!AND(HasValue(Email),HasValue(Phone))}
Result: True only if both fields have values
Level 4: Conditional with Nested Function
Scenario: Display email if it exists, otherwise display phone
Formula:{!If(HasValue(Email),Email,Phone)}
Result: Returns Email if exists, otherwise returns Phone
Level 5: Complex Multi-Condition Validation
Scenario: When Stage is "Closed Won", both Amount and Close Date are required
Formula:{!AND(Equal(Stage,"Closed Won"),OR(IsNull(Amount),IsNull(CloseDate)))}
Result: True (error) when Stage is "Closed Won" and either field is empty
Level 6: Complex Nested Conditionals
Scenario: Categorize opportunities by amount: Small (<$10K), Medium ($10K-$100K), Large (>$100K)
Formula:
{!If(LessThan(Amount,10000),"Small",If(LessThan(Amount,100000),"Medium","Large"))}
Result: Returns appropriate category based on amount
Level 7: Advanced Multi-Level Logic
Scenario: Validation requiring different fields based on multiple conditions
Formula:
{!AND(Equal(Type,"Customer"),Equal(Stage,"Closed Won"),OR(IsNull(ContractNumber),IsNull(PurchaseOrder)))}
Result: True (error) when Type is "Customer", Stage is "Closed Won", and either ContractNumber or PurchaseOrder is empty
Best Practices for Writing Functions
Start Simple, Build Complexity
Begin with the simplest version of your formula that works, then add complexity incrementally. Test each addition before proceeding.
Example Progression:
{!IsNull(Email)} - Test basic condition{!AND(IsNull(Email),IsNull(Phone))} - Add second condition{!AND(Equal(Type,"Customer"),AND(IsNull(Email),IsNull(Phone)))} - Add conditional wrapper
Use Parentheses Carefully
Every opening parenthesis must have a matching closing parenthesis. Nested functions require careful parenthesis tracking.
Good Practice: Count opening and closing parentheses to ensure they match.
Mind Your Commas
Function arguments are separated by commas with no spaces. Missing or extra commas cause syntax errors.
Correct:{!Equal(Status,"Active")}
Wrong:{!Equal(Status, "Active")} (space after comma)
Wrong:{!Equal(Status "Active")} (missing comma)
Quote Text Strings Properly
Text strings must be enclosed in double quotation marks. Text without quotes is interpreted as field names.
Correct:{!Equal(Status,"Active")} - Comparing to text "Active"
Wrong:{!Equal(Status,Active)} - Comparing to field named Active
Test with Real Data
Test formulas with actual records containing:
- Empty/null values
- Minimum and maximum values
- Boundary conditions
- Different data types
- Multiple user roles
Use Meaningful Field Names
When creating custom fields that will be used in formulas, use clear, descriptive names that make formulas self-documenting.
Good:{!Equal(AccountStatus__c,"Active")}
Less Clear:{!Equal(Status__c,"A")}
Document Complex Formulas
For complex validation rules or formulas, document the business logic in the Description field explaining what the formula does and why.
Consider Readability vs. Efficiency
While nested functions are powerful, deeply nested formulas can be difficult to understand and maintain. Sometimes multiple simpler formulas are better than one complex formula.
Next Steps
Now that you understand functions and how to combine them with merge fields, proceed to Functions and Merge Fields Troubleshooting to learn debugging techniques, common errors, and optimization strategies.
<< Understanding Merge Fields | Troubleshooting and Best Practices >>