Formulas (& calculated fields)¶
In the Mythradon Entity Manager, it's possible to define business logic that will execute before a record is saved. This logic is defined in a formula for a specific entity.
It provides the ability to automatically set specific fields (attributes) with values derived from calculation. Some functions can also perform actions like send a Push Notification.
To edit a formula for a specific entity:
- Select
Administration | Entity Manager
from the Menu Button - Select the required entity type
- Click the
Formula
button - Define the required formula. Select the required attributes or functions using the
+
button. - Click the
Save
button.
You may also need to set field values for calculated (read-only) fields.
System Administrators can run the Recalculate Formula action for specific records from the list view:
- Select records (or all search results)
- Select
Actions
from the dropdown menu - Select
Recalculate Formula
.
This documentation covers:
- Formula Syntax
- Operators
- Attributes
- Calculated Fields
- Formula Sandbox
- Functions
- Values
- Variables
- Comments
- Function arguments
- Comparison
- Examples
- Explanation
Syntax¶
Formulas in Mythradon are written in a simple language designed specifically for this feature.
There are 4 element types (lexemes) that can be used in formula:
- operators
- functions
- values (scalars and NULL value)
- attributes
Separated expressions must be delimited by character ;
.
Example:
string\concatenate(name, ' + ', $test);
where:
string\concatenate
– a functionname
– an attribute (of a target entity, to which formula is applied)' + '
– a value (of string type)$test
– a variable (supposed to be declared somewhere above)
Available scalar types:
- string –
'string'
- int –
1000
- float –
1000.5
- boolean –
true
orfalse
Operators¶
=
- assignment??
- null coalescing||
- logical OR&&
- logical AND!
- logical NOT+
- numeric summation-
- numeric subtraction*
- numeric multiplication/
- numeric division%
- numeric modulo==
- comparison equals!=
- comparison not equals>
- comparison greater than<
- comparison less than>=
- comparison greater than or equals<=
- comparison less than or equals
Arithmetic Operators¶
The following table shows all the arithmetic operators supported by the Mythradon formula language. Assume variable A holds 10 and variable B holds 20 then:
Operator | Description | Example |
---|---|---|
+ |
Adds two numeric operands. Use string\concatenate() for strings. |
A + B = 30 |
- |
Subtracts second operand from the first | A - B = -10 |
* |
Multiplies both operands | A * B = 200 |
/ |
Divides numerator by de-numerator | B / A = 2 |
% |
Modulus Operator and remainder of after an integer division | B % A = 0 |
Unary Operators¶
The following table shows all the unary operators supported by the Mythradon formula language.
Operator | Description | Example |
---|---|---|
+ |
Returns the value of its operand. | +4 = 4 |
- |
Computes the numeric negation of its operand. | -4 = -4 , -(-4) = 4 |
Relational Operators¶
The following table shows all the relational operators supported by the Mythradon formula language. Assume variable A holds 10 and variable B holds 20 then:
Operator | Description | Example |
---|---|---|
== |
Checks if the values of two operands are equal or not. If yes, then the condition becomes true. | (A == B) is not true |
!= |
Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. | (A != B) is true |
> |
Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. | (A > B) is not true |
< |
Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. | (A < B) is true |
>= |
Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. | (A >= B) is not true |
<= |
Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. | (A <= B) is true |
Logical Operators¶
Following table shows all the logical operators supported by Mythradon formula language. Assume variable A holds 1 and variable B holds 0 then:
Operator | Description | Example |
---|---|---|
&& |
Called Logical AND operator. If both the operands are true (non-zero), then the condition becomes true. | (A && B) is false |
|| |
Checks if the values of two operands are equal or not. If yes, then the condition becomes true. | (A || B) is true |
! |
Checks if the values of two operands are equal or not. If yes, then the condition becomes true. | (A == B) is not true |
Assignment Operators¶
The following table lists the assignment operators supported by the Mythradon formula language.
Operator | Description | Example |
---|---|---|
= |
Simple assignment operator. Assigns values from right side operands to left side operand. | C = A + B will assign the value of A + B to C |
?? |
Null Coalescing Operator. (Refer below for details) | null ?? 1 = 1 2 ?? 1 = 2 |
Null Coalescing Operator¶
A Null Coalescing Operator ??
is a syntactic construct that provides a concise way to check for null or undefined values and set a default value when they are encountered. It is often used in conditional statements, assignments, and function parameters to simplify null checking code.
The operator works by evaluating the expression on the left-hand side (LHS) of the operator, and if it is null or undefined, it returns the expression on the right-hand side (RHS) of the operator. If the LHS is not null or undefined, the operator returns the value of the LHS.
Example 1:
null ?? 1; // resolves to 1
2 ?? 1; // resolves to 2
Example 2:
$name = null;
$defaultName = "Guest";
$finalName = $name ?? $defaultName; // $finalName will be "Guest"
In this example, the null coalescing operator checks if the $name variable is null or undefined. Since it is, it returns the value of $defaultName, which is "Guest". If $name had a non-null value, the operator would return its value instead.
Operator Precedence¶
Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. An operator's precedence is meaningful only if other operators with higher or lower precedence are present.
Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.
For example, $x = 7 + 3 * 2;
here, $x
is assigned 13
, not 20
because operator *
has a higher precedence than +
, so it first gets multiplied with 3 * 2
and then adds 7
.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Note: The recommended approach is to avoid depending on natural operator precedence and instead use parentheses to explicitly specify the order of operations. i.e. Instead of using
$x = 7 + 3 * 2;
use$x = 7 + (3 * 2);
.
Category | Operator | Associativity |
---|---|---|
Postfix | () |
Left to right |
Unary | + - ! |
Right to left |
Multiplicative | * / % |
Left to right |
Additive | + - |
Left to right |
Relational | < <= >= > |
Left to right |
Equality | == != |
Left to right |
Logical AND | && |
Left to right |
Logical OR | || |
Left to right |
NULL Coalescing | ?? |
Right to left |
Assignment | = |
Right to left |
Attributes¶
Attributes represent fields in a target entity, and you can insert them by clicking on the plus button and selecting from the available data types.
Using the format linkName.attributeName
, it is possible to access the attributes of related entities.
The introduction of the attribute lexeme allows for simplified writing, such as this:
description = 'test';
If we didn't have attributes we would need to write more verbose:
entity\setAttribute('description', 'test');
Calculated Fields¶
Mythradon doesn't perform field calculations when retrieving a record. As a result, any field that requires a calculated value from other fields or records should be created as a standard field, and then populated using a formula that runs when the record is saved.
Example:
Assume that you need a FullName
field on a Contact record that currently has only has FirstName
and LastName
fields.
Note: Creating a
FullName
field on a Contact entity is not a great example as it already has such a field. However the following does show the process of creating a calculated field.
- Using the Entity Manager, create a new varchar field called
FullName
and set it toRead-Only
. Although the field will be read-only on the user interface, it will be set by the formula. - In the Formula area on the same entity enter the following formula:
ifThen((entity\isAttributeChanged('firstName') || entity\isAttributeChanged('lastName')),
fullNameCust = string\trim(string\concatenate(firstName, ' ', lastName));
);
- Click the
Check Syntax
button to validate your formula before saving. - Add the new
FullName
field to a layout for the purposes of debugging
Now when you create or edit a Contact record and you make a change to either the firstName
or lastName
fields the fullNameCust
field will be updated.
Formula Sandbox¶
The Formula Sandbox is a feature designed for administrators that enables them to create and test formulas without implementing them directly on an Entity, which could affect all users of the system.
With the Formula Sandbox, you can create formulas that target a specific record, which can save time when developing formulas.
To access the Formula Sandbox:
- Select
Administration | Formula Sandbox
from the Menu Button
- Create your required formula
- If required, select a specific entity to test against
- Click the
Check Syntax
button to validate the syntax of your formula - Click the
Run
button to execute the formula
Note: The Formula Sandbox executes actual code, which means that any records created or updated through it are physically stored and updated in the database.
Functions¶
Format of function use: groupName\functionName(argument1, argument2, ..., argumentN)
.
The supported functions are calssified into the following groups:
- Array
- Datetime
- Entity
- Env
- Ext
- General
- Json
- Language
- Number
- Object
- Output
- Password
- Record
- String
- Util
Array¶
An array is a data structure that stores a collection of elements of the same data type, such as integers, characters, or strings. The elements are arranged in a contiguous block of memory, with each element occupying a specific position within the array. The position of each element is identified by its index, which is a non-negative integer value that starts from 0 for the first element and increases by 1 for each subsequent element.
Arrays are commonly used to store a list of records that can be easily accessed and manipulated using loops and other programming constructs. They offer an efficient way to access and process data, as well as to organise and manage it.
Mythradon support the following array functions:
- array\at
- array\includes
- array\indexOf
- array\join
- array\length
- array\push
- array\removeAt
- array\unique
Note: Use the
list()
function to create a new array.
array\at¶
array\at(LIST, INDEX)
This function returns the value in the LIST based on the provided INDEX. It's important to note that the first element in the array has an index of 0.
Example:
$list = array\push($list, 'one','two','three','four');
$value = array\at($list, 2); // $value will be 'three'
output\printLine($value);
Note: Passing an array argument by reference is not supported. Therefore, you will need to reassign the array to the result returned by the function.
array\includes¶
array\includes(LIST, VALUE)
Returns true if LIST contains VALUE. Can be used for Array and Multi-Enum fields.
array\indexOf¶
array\indexOf(LIST, ELEMENT)
This function can be used to return the position of a specified ELEMENT within a LIST in Mythradon. If the ELEMENT is not found within the LIST, the function will return null. This function is compatible with both Array and Multi-Enum fields.
Example:
$numberList = array\push($idList, 'one','two','three','four');
$value = array\indexOf($numberList, 'three'); // $value will be 2
output\printLine($value);
Note: In Mythradon, arrays begin at zero.
array\join¶
array\join(LIST, SEPARATOR)
Joins array elements with a string separator. Returns a string.
Example:
$string = array\join($array, $separator);
array\length¶
array\length(LIST)
Returns the number of elements in LIST.
array\push¶
array\push(LIST, VALUE1 [, VALUE2 ...])
Adds one or more elements to the end of an array and returns the new array.
Important: An array argument is not passed by reference. You need to re-assign the array to a function result.
Example:
$list = array\push($list, 'test');
array\removeAt¶
array\removeAt(LIST, INDEX)
This function removes an element from the array based on its INDEX and returns a new array with the updated elements.
Example 1:
$newArray = array\removeAt($array, $index);
Example 2:
$numberList = array\push($idList, 'one','two','three','four');
$value = array\indexOf($numberList, 'three');
output\printLine($value); // $value will be 2
$newArray = array\removeAt($numberList, $value);
output\printLine($newArray); // $newArray = ["one","two","four"]
array\unique¶
array\unique(LIST)
This function takes a LIST as input, removes any duplicate elements, and returns a new array with only the unique elements.
Example 1:
$newArray = array\unique($array);
Example 2:
$list = List(9,6,7,2,9,9,8,3,4,1,8,7,4,2,1);
$newArray = array\unique($list);
output\printLine($newArray); // $newArray = [9,6,7,2,8,3,4,1]
Datetime¶
- datetime\addDays
- datetime\addHours
- datetime\addMinutes
- datetime\addMonths
- datetime\addWeeks
- datetime\addYears
- datetime\closest
- datetime\date
- datetime\dayOfWeek
- datetime\diff
- datetime\format
- datetime\hour
- datetime\minute
- datetime\month
- datetime\now
- datetime\today
- datetime\year
Note: In Mythradon, date and date-time values are represented as strings in the format YYYY-MM-DD HH:MM. i.e.
'2021-01-01'
,'2021-01-01 10:00'
.
datetime\addDays¶
datetime\addDays(VALUE, DAYS)
Adds DAYS to date or datetime VALUE. DAYS can be negative.
datetime\addHours¶
datetime\addHours(VALUE, HOURS)
Adds HOURS to datetime VALUE. HOURS can be negative. Returns a modified STRING value.
datetime\addMinutes¶
datetime\addMinutes(VALUE, MINUTES)
Adds MINUTES to datetime VALUE. MINUTES can be negative. Returns a modified STRING value.
Example:
$modifiedValue = datetime\addMinutes('2021-01-01 00:00', 10)
datetime\addMonths¶
datetime\addMonths(VALUE, MONTHS)
Adds MONTHS to date or datetime VALUE. MONTHS can be negative. Returns a modified STRING value.
datetime\addWeeks¶
datetime\addWeeks(VALUE, WEEKS)
Adds WEEKS to date or datetime VALUE. WEEKS can be negative. Returns a modified STRING value.
datetime\addYears¶
datetime\addYears(VALUE, YEARS)
Adds YEARS to date or datetime VALUE. YEARS can be negative. Returns a modified STRING value.
datetime\closest¶
datetime\closest(VALUE, TYPE, TARGET, [IS_PAST], [TIMEZONE])
Returns the closest date or datetime to VALUE based on passed arguments.
TYPE can be one of the following values: 'time', 'minute', 'hour', 'date', 'month', 'dayOfWeek'. TARGET is an integer value or a string value. IS_PAST means to find the closest in the past. If TIMEZONE is omitted, then default timezone is used.
Examples:
datetime\closest(datetime\now(), 'time', '20:00') // Returns the closest datetime value in the future with 20:00 time.
datetime\closest('2017-11-20', 'date', 1, true) // Returns '2017-11-01', the first day of the month.
datetime\closest(datetime\now(), 'dayOfWeek', 1) // Returns the next Monday (the beginning of the day).
datetime\date¶
datetime\date(VALUE, [TIMEZONE])
Returns date of the month (1-31). 0
if VALUE is empty. If TIMEZONE is omitted, then system timezone is used.
datetime\dayOfWeek¶
datetime\dayOfWeek(VALUE, [TIMEZONE])
Returns day of the week (0-6). -1
if VALUE is empty. 0
- for Sunday. If TIMEZONE is omitted, then system timezone is used.
datetime\diff¶
datetime\diff(VALUE_1, VALUE_2, INTERVAL_TYPE)
Returns the difference between two dates or datetimes. INTERVAL_TYPE can be 'years', 'months', 'days', 'hours', 'minutes'. Returns null
if failure. The result will be negative if VALUE_1 < VALUE_2.
datetime\format¶
datetime\format(VALUE, [TIMEZONE], [FORMAT])
Converts date or datetime VALUE into a string formatted according to the application settings or a given timezone and format. TIMEZONE and FORMAT can be omitted. If TIMEZONE is omitted, then default time zone will be used. If FORMAT is omitted, then default format will be used.
Examples:
datetime\format(closeDate, 'America/New_York', 'MM/DD/YYYY')
datetime\format(dateStart, 'America/New_York', 'MM/DD/YYYY hh:mma')
datetime\format(dateStart, 'Europe/Amsterdam', 'DD/MM/YYYY HH:mm')
datetime\hour¶
datetime\hour(VALUE, [TIMEZONE])
Returns hour (0-23). -1
if VALUE is empty. If TIMEZONE is omitted, then system timezone is used.
datetime\minute¶
datetime\minute(VALUE, [TIMEZONE])
Returns minute (0-59). -1
if VALUE is empty. If TIMEZONE is omitted, then system timezone is used.
datetime\month¶
datetime\month(VALUE, [TIMEZONE])
Returns month (1-12). 0
if VALUE is empty. If TIMEZONE is omitted, then system timezone is used.
datetime\now¶
datetime\now()
Returns current datetime.
datetime\today¶
datetime\today()
Returns today's date (w/o time).
datetime\year¶
datetime\year(VALUE, [TIMEZONE])
Returns year. 0
if VALUE is empty. If TIMEZONE is omitted, then system timezone is used.
Entity¶
Functions of the Entity group operate with a target record. There can be only one target record available in formula-script context. For Before Update Script, the target record is the record that is currently updated. For Workflow's Create Record action, the target record is the record is being created. For Workflow's conditions, the target record is the target record of the workflow rule.
- entity\addLinkMultipleId
- entity\attribute
- entity\attributeFetched
- entity\countRelated
- entity\getLinkColumn
- entity\hasLinkMultipleId
- entity\isAttributeChanged
- entity\isAttributeNotChanged
- entity\isNew
- entity\isRelated
- entity\removeLinkMultipleId
- entity\setAttribute
- entity\sumRelated
entity\addLinkMultipleId¶
entity\addLinkMultipleId(LINK, ID)
Adds ID to Link Multiple field.
entity\addLinkMultipleId(LINK, ID_LIST)
Adds the list of ids.
Example:
entity\addLinkMultipleId('teams', 'someTeamId');
Add 'someTeamId' to 'teams' field.
entity\attribute¶
entity\attribute(ATTRIBUTE): MIXED
Returns the ATTRIBUTE value of a target record. It's also possibe to fetch an attribute of a related record.
$test = entity\attribute('name')
is equivalent to $test = name
.
Examples:
$assignedUserId = entity\attribute('assignedUserId');
$accountName = entity\attribute('account.name');
entity\attributeFetched¶
entity\attributeFetched(ATTRIBUTE): MIXED
An ATTRIBUTE value that was set when a target record was fetched from database. Before it was modified.
Example:
$originalAssignedUserId = entity\attributeFetched('assignedUserId');
entity\countRelated¶
entity\countRelated(LINK, [FILTER]): INTEGER
Returns a number of related records with an optional FILTER applied.
Example:
$numberOfOpenOpportunities = entity\countRelated('opportunities', 'open');
entity\getLinkColumn¶
entity\getLinkColumn(LINK, ID, COLUMN): MIXED
Fetches a relationship column value. Return type is mixed.
Example:
entity\getLinkColumn('targetLists', 'TARGET_LIST_ID', 'optedOut');
entity\hasLinkMultipleId¶
entity\hasLinkMultipleId(LINK, ID): BOOLEAN
Checks whether a Link Multiple field has a specific ID. Returns a boolean (True or False).
entity\isAttributeChanged¶
entity\isAttributeChanged(ATTRIBUTE): BOOLEAN
Returns TRUE if the ATTRIBUTE of the record was changed.
Example:
$statusChanged = entity\isAttributeChanged('status');
$statusChanged = entity\isAttributeChanged(status); // Invalid because ATTRIBUTE is not a string or constant. Missing quotes.
Note: The ATTRIBUTE is a STRING value that needs to be enclosed in quotes or a variable.
entity\isAttributeNotChanged¶
entity\isAttributeNotChanged(ATTRIBUTE): BOOLEAN
Return TRUE if the ATTRIBUTE of the record was not changed.
entity\isNew¶
entity\isNew()
Returns TRUE if the entity is new (being created) and FALSE if not (being updated).
entity\isRelated¶
entity\isRelated(LINK, ID)
Checks whether a target entity is related with another entity represented by LINK and ID.
entity\removeLinkMultipleId¶
entity\removeLinkMultipleId(LINK, ID)
Removes a specific ID from the Link Multiple field.
entity\setAttribute¶
entity\setAttribute(ATTRIBUTE, VALUE)
Set ATTRIBUTE with a VALUE.
entity\setAttribute('stage', 'Closed Won')
is equivalent to stage = 'Closed Won'
.
Example:
entity\setAttribute('stage', 'Closed Won');
entity\sumRelated¶
entity\sumRelated(LINK, FIELD, [FILTER])
Sums related records by a specified FIELD with an optional FILTER.
Example:
entity\sumRelated('opportunities', 'amountConverted', 'won')
FILTER is a name of a filter pre-defined in the system.
Env¶
env\userAttribute¶
env\userAttribute(ATTRIBUTE)
Returns the value of the specified ATTRIBUTE of the current user.
Examples:
// Return the ID for the Current User
$userId = env\userAttribute('id');
$userId = string\concatenate('UserId: ', $userId);
output\printLine($userId); // Outputs 'UserId: ' + the ID for the Current User
// Return the Name for the Current User
$userName = env\userAttribute('name');
$userName = string\concatenate('UserName: ', $userName);
output\printLine($userName); // Outputs 'UserName: ' + the Name for the Current User
// Return the Type of the Current User. This can be used to determine if the user is a portal user
$userType = env\userAttribute('type');
output\printLine($userType);
Other attributes that are available include:
- id
- createdAt
- emailAddress
- firstName
- gender
- ipAddress
- isActive
- lastName
- limitedAdmin
- limitedAdminPermissions
- middleName
- modifiedAt
- name
- password
- phoneNumber
- portal
- salutationName
- title
- type
- userName
Ext¶
The Ext function group include a range of general extension functions that include sending of Emails, SMS messages, generating PDF documents and working with the Working Time calendars.
- ext\account\findByEmailAddressDomain
- ext\currency\convert
- ext\email\send
- ext\email\applyTemplate
- ext\pdf\generate
- ext\sms\send
- ext\user\sendAccessInfo
- ext\workingTime\addWorkingDays
- ext\workingTime\findClosestWorkingTime
- ext\workingTime\getSummedWorkingHours
- ext\workingTime\getWorkingDays
- ext\workingTime\hasWorkingTime
- ext\workingTime\isWorkingDay
ext\account\findByEmailAddressDomain¶
ext\account\findByEmailAddressDomain(EMAIL_ADDRESS)
Finds an account by an email address. If no full match found, then tries to find by domain name. Free email provider domains are ignored. Returns ID or null.
ext\currency\convert¶
ext\currency\convert(AMOUNT, FROM_CODE, [TO_CODE])
Converts a currency amount from one currency code (FROM_CODE) to another currency code (TO_CODE). If TO_CODE is omitted, then the system default currency is used. Returns an amount represented as string.
Example:
$convertedValueString = ext\currency\convert(amount, amountCurrency);
$convertedValue = number\parseFloat($convertedValue);
ext\email\send¶
ext\email\send(EMAIL_ID)
Sends an email. EMAIL_ID is an ID of the email record. Returns TRUE if sent, false if not sent.
If from address is not set in the email, then system email address will be used. If there's match between from address and the address of some group email account, then SMTP setting of the group email account will be used.
Example:
$id = record\create(
'Email',
'from', 'from-address@test.com',
'to', 'to-address@test.com',
'subject', 'Test from formula',
'body', 'Hi,\n\nThis is a test.',
'isHtml', false,
'status', 'Sending'
);
ext\email\send($id);
ext\email\applyTemplate¶
ext\email\applyTemplate(EMAIL_ID, EMAIL_TEMPLATE_ID, [PARENT_TYPE, PARENT_ID])
Applies an email template to an existng email record. Parent record can be passed optionally.
Example:
$emailId = record\create(
'Email',
'to', 'to-address@test.com',
'status', 'Draft',
'parentId', entity\attribute('id'),
'parentType', 'Case'
);
ext\email\applyTemplate($emailId, 'some-email-template-id');
ext\email\send($emailId);
ext\pdf\generate¶
ext\pdf\generate(ENTITY_TYPE, ENTITY_ID, TEMPLATE_ID, [FILENAME])
Generates PDF file and returns attachment ID. If failed, then returns NULL. TEMPLATE_ID is an ID of PDF template.
Example:
$attachmentId = ext\pdf\generate(
'Lead', entity\attribute('id'), 'pdf-template-id', 'test.pdf'
);
$emailId = record\create('Email',
'subject', 'Test PDF',
'body', 'PDF is attached',
'to', entity\attribute('emailAddress'),
'attachmentsIds', list($attachmentId)
);
ext\email\send($emailId);
ext\sms\send¶
ext\sms\send(SMS_ID): BOOLEAN
Sends an SMD. SMS_ID is the ID of an SMS record. Returns TRUE if sent, false if not sent.
Example:
$smsId = record\create(
'Sms',
'to', '+1 000 111 222',
'body', 'This is a test from Mythradon.'
);
ext\sms\send($smsId);
If from address is not set in the SMS, then the system SMS from number will be used.
ext\user\sendAccessInfo¶
ext\user\sendAccessInfo($userId)
This function will send the standard access information email to the specified User Id. This works for both standard Users and Portal Users.
There is the possibility of two email templates that could be used depending if the User is a standard User or Portal User.
- Access Info - template for standard Users
- Access Info for Portal - template for standard Users
To access this email template:
- Select
Administration | Template Manager
from the Menu Button - Select
Access Info
for standard Users orAccess Info for Portals
for Portal Users
ext\workingTime\addWorkingDays¶
ext\workingTime\addWorkingDays(DATE, DAYS, [ENTITY_TYPE, ENTITY_ID]): STRING|NULL
The purpose of this function is to complement the Working Calendar feature. It accepts a DATE and a number of DAYS as inputs and computes a new date-time by adding the specified number of working days to the input DATE. The resulting date-time string will indicate the start of the day (00:00
) in the relevant time zone.
Example:
$dueDate = ext\workingTime\addWorkingDays(datetime\now(), 10);
Working Time Calendars operate at three levels:
- Default - System Level Working Time Calendar
- Team - Team Level Working Time Calendar
- User - User Level Working Time Calendar
The optional parameters [ENTITY_TYPE] and [ENTITY_ID] can be either 'User'
or 'Team'
followed by the Id of the specific User or Team.
Example:
$currentDate = datetime\today();
$currentDateTimStr = string\concatenate('Current Date/Time: ', $currentDate);
output\printLine($currentDateTimStr);
// This due date will be calculated using the Default System Working Time Calendar
$dueDate = ext\workingTime\addWorkingDays($currentDate, 10);
$dueDateTimStr = string\concatenate('Due Date: ', $dueDate);
output\printLine($dueDateTimStr);
// This due date will be calculated using a specific Team level Working Time Calendar
$entityType = 'Team';
$teamId = '5f137834ed903a606';
$dueDate = ext\workingTime\addWorkingDays($currentDate, 10, $entityType, $teamId);
$dueDateTimStr = string\concatenate('Due Date: ', $dueDate);
output\printLine($dueDateTimStr);
// This due date will be calculated using a specific User level Working Time Calendar
$entityType = 'User';
$userId = entity\attribute('Id');
$dueDate = ext\workingTime\addWorkingDays($currentDate, 10, $entityType, $userId);
$dueDateTimStr = string\concatenate('Due Date: ', $dueDate);
output\printLine($dueDateTimStr);
Note: If the formula fails to create a new datetime value, check that you have a default Working Time Calendar defined in
Administration | Settings
.
Click here for more information on Working Time Calendars
ext\workingTime\findClosestWorkingTime¶
ext\workingTime\findClosestWorkingTime(DATE, [ENTITY_TYPE, ENTITY_ID]): STRING|NULL
ext\workingTime\findClosestWorkingTime(DATE) – finds the beginning of the next closest working time slot;
Example:
$nextWorkingTimeSlot = ext\workingTime\findClosestWorkingTime(datetime\now());
Working Time Calendars operate at three levels:
- Default - System Level Working Time Calendar
- Team - Team Level Working Time Calendar
- User - User Level Working Time Calendar
The optional parameters [ENTITY_TYPE] and [ENTITY_ID] can be either 'User'
or 'Team'
followed by the Id of the specific User or Team.
ext\workingTime\getSummedWorkingHours¶
ext\workingTime\getSummedWorkingHours(FROM, TO, [ENTITY_TYPE, ENTITY_ID]): FLOAT
ext\workingTime\getSummedWorkingHours(FROM, TO) – get a total number of working hours between two dates;
Example:
$totalWorkingHours = ext\workingTime\getSummedWorkingHours(datetime\now(), datetime\addDays(datetime\now(), 10));
Working Time Calendars operate at three levels:
- Default - System Level Working Time Calendar
- Team - Team Level Working Time Calendar
- User - User Level Working Time Calendar
The optional parameters [ENTITY_TYPE] and [ENTITY_ID] can be either 'User'
or 'Team'
followed by the Id of the specific User or Team.
ext\workingTime\getWorkingDays¶
ext\workingTime\getWorkingDays(FROM, TO, [ENTITY_TYPE, ENTITY_ID]): INTEGER
Returns the number of working days between two dates.
Example:
$currentDate = datetime\today();
$dueDate = ext\workingTime\addWorkingDays($currentDate, 10);
$numberOfWorkingDays = ext\workingTime\getWorkingDays($currentDate, $dueDate);
Working Time Calendars operate at three levels:
- Default - System Level Working Time Calendar
- Team - Team Level Working Time Calendar
- User - User Level Working Time Calendar
The optional parameters [ENTITY_TYPE] and [ENTITY_ID] can be either 'User'
or 'Team'
followed by the Id of the specific User or Team.
ext\workingTime\hasWorkingTime¶
ext\workingTime\hasWorkingTime(FROM, TO, [ENTITY_TYPE, ENTITY_ID]): BOOLEAN
This function determines whether a date range includes any working hours and returns a boolean value accordingly.
Example:
$currentDate = datetime\today();
$dueDate = datetime\addDays($currentDate, 20);
$hasWorkingTime = ext\workingTime\hasWorkingTime($currentDate, $dueDate);
Working Time Calendars operate at three levels:
- Default - System Level Working Time Calendar
- Team - Team Level Working Time Calendar
- User - User Level Working Time Calendar
The optional parameters [ENTITY_TYPE] and [ENTITY_ID] can be either 'User'
or 'Team'
followed by the Id of the specific User or Team.
ext\workingTime\isWorkingDay¶
ext\workingTime\isWorkingDay(FROM, TO, [ENTITY_TYPE, ENTITY_ID]): BOOLEAN
This function determines whether a date falls into a working day and returns a boolean value accordingly.
Example:
$currentDate = datetime\today();
$dueDate = datetime\addDays($currentDate, 20);
$isWorkingDay = ext\workingTime\isWorkingDay($currentDate, $dueDate);
Working Time Calendars operate at three levels:
- Default - System Level Working Time Calendar
- Team - Team Level Working Time Calendar
- User - User Level Working Time Calendar
The optional parameters [ENTITY_TYPE] and [ENTITY_ID] can be either 'User'
or 'Team'
followed by the Id of the specific User or Team.
General¶
ifThenElse¶
ifThenElse(CONDITION, CONSEQUENT, ALTERNATIVE)
If CONDITION is met, then do CONSEQUENT. If not - then do ALTERNATIVE.
Example:
ifThenElse($someVariable == 'someValue', // if condition is true
$anotherVariable = 1, // do this
$anotherVariable = 2 // otherwise do this
)
CONSEQUENT and ALTERNATIVE can consist of mutliple commands separated by the semicolon ;
.
ifThen¶
ifThen(CONDITION, CONSEQUENT)
If CONDITION is met, then do CONSEQUENT. If not - do nothing.
CONSEQUENT can consist of mutliple commands separated by the semicolon ;
.
list¶
list(VALUE-1[, ... VALUE-N])
Returns an array. Values are passed as arguments to the function.
Example:
$list = list(0, 1, 2); // will return array [0, 1, 2]
Useful to create an array for link-multiple IDs.
Example:
teamsIds = list($teamId) // `['team-id']`
while¶
while(CONDITION, STATEMENT)
Executes STATEMENT repeatedly as long CONDITION is true.
Example:
// Copy the elements from $source to $target
$source = list(0, 1, 2);
$target = list();
$i = 0;
while($i < array\length($source),
$target = array\push(
$target,
array\at($source, $i)
);
$i = $i + 1;
);
Json¶
json\encode¶
json\encode(VALUE): STRING
Given a VALUE as input, this function encodes it in JSON format and returns the encoded string.
$encodedValue = json\encode($someValue);
json\retrieve¶
json\retrieve(JSON, PATH): MIXED
Retrieves a specific attribute from a JSON string. PATH is a string, items are separated by dots.
Example, retrieving id from {"id": "SOME_ID"}
:
$value = json\retrieve($someJsonString, 'id');`
Example, retrieving id from [{"id": "SOME_ID"}]
:
$value = json\retrieve($someJsonString, '0.id');`
Language¶
language\translate¶
language\translate(LABEL, [CATEGORY, SCOPE]): STRING
Translates a label to the language set as default.
Example:
language\translate('passwordWillBeSent', 'messages', 'User')
language\translateOption¶
language\translateOption(OPTION, FIELD, [SCOPE])
Translates an option of a specific field to the language set as default. The field can be of the following types: Enum, Multi-enum, Checklist, Array, Varchar.
Example:
language\translateOption('Customer', 'type', 'Account')
Number¶
- number\abs
- number\ceil
- number\floor
- number\format
- number\parseFloat
- number\parseInt
- number\randomInt
- number\round
number\abs¶
number\abs(VALUE): INTEGER|FLOAT
Absolute value. Returns null if VALUE is not numeric.
The abs()
or absolute function is a mathematical function that returns the positive value of a given number, regardless of its sign. In other words, if the input value is negative, the absolute function converts it to its positive counterpart, while if the input value is already positive, it remains unchanged.
For instance, if the input value is -5, the abs()
function would return 5, whereas if the input value is 7, the function would return 7 as it is already positive. The absolute function is commonly used in programming languages, mathematics, and other scientific applications where it is necessary to obtain the magnitude or distance of a value from zero.
The abs()
function works with both integers and floating point numbers.
Examples:
$val = number\abs(55.3); // Returns 55.3
$val = number\abs(-55.3); // Returns 55.3
number\ceil¶
number\ceil(VALUE): INTEGER
The ceil()
function is a mathematical function that rounds a given number up to the next integer.
In its most common usage, the ceil()
function returns the smallest integer that is greater than or equal to the input value. For example, if the input value is 3.2, the ceil() function would return 4, while if the input value is -4.5, the function would return -4, because -4 is the smallest integer greater than or equal to -4.5.
Examples:
$val = number\ceil(4.5); // Returns 5
$val = number\ceil(-4.5); // Returns 4
number\floor¶
number\floor(VALUE): INTEGER
This function rounds down a given number to the nearest integer value. This method is commonly used in situations where precise integer values are required, such as in financial calculations, or in situations where a non-integer value must be converted to an integer.
For example, if we apply the floor()
method to the number 3.8, it will return 3 as the next lowest integer value. Similarly, if we apply the floor()
method to -2.5, it will return -3 as the next lowest integer value.
Examples:
$val = number\floor(4.5); // Returns 4
$val = number\floor(-4.5); // Returns -5
number\format¶
number\format(VALUE, [DECIMALS], [DECIMAL_MARK], [THOUSAND_SEPARATOR]): STRING
Converts numeric VALUE into string formatted according to a specific format or default application settings. If DECIMALS, DECIMAL_MARK OR THOUSAND_SEPARATOR, then system defaults are used.
Examples:
number\format(2.666667, 2); // Returns 2.67;
number\format(1000, 2); // Returns 1,000.00;
number\format(10.1, 0); // Returns 10.
number\parseInt¶
number\parseInt(STRING): INTEGER
This function converts a string to an integer.
Examples:
$myInteger = number\parseInt("234"); // Returns 234
$myInteger = number\parseInt("234.32"); // Returns 234
number\parseFloat¶
number\parseFloat(STRING): FLOAT
This function converts a string to an float.
Example:
$myFloat = number\parseFloat("234.32"); Returns 234.32
number\randomInt¶
number\randomInt([MIN, MAX]): INTEGER
Generates a cryptographic random integer between specified MIN and MAX. If MIN is omitted, then 0
is used.
The randomInt()
function takes in two parameters, the minimum and maximum values of the desired range, and then returns a random integer that falls within that range, inclusive of the minimum and maximum values. For example, if the minimum value is 1 and the maximum value is 10, the randomInt() function would generate a random integer between 1 and 10, such as 4 or 9.
number\round¶
number\round(VALUE, PRECISION): INTEGER|FLOAT
Returns the rounded value of VALUE to specified PRECISION (number of digits after the decimal point). PRECISION can also be negative or zero (default).
The round()
function is a mathematical function that rounds a given value to a specified number of decimal places or to the nearest integer, depending on the precision parameter.
The function takes two parameters, the first is the value that needs to be rounded, and the second is the precision parameter that determines the number of decimal places to which the value should be rounded. If the precision parameter is not specified, the function rounds the value to the nearest integer.
The round()
function returns an integer or a float value, depending on the input parameters and the type of rounding performed. If the precision parameter is greater than or equal to zero, the function rounds the value to the specified number of decimal places and returns a float value. On the other hand, if the precision parameter is less than zero, the function rounds the value to the nearest integer and returns an integer value.
For example, if the value is 3.14159 and the precision is 2, the round()
function would return 3.14. If the precision is -1, the function would round the value to the nearest integer and return 3.
Examples:
$val = number\round(3.14159); // Returns 3
$val = number\round(3.14159, 1); // Returns 3.1
$val = number\round(3.14159, 2); // Returns 3.14
$val = number\round(3.14159, 3); // Returns 3.142
$val = number\round(3.14159, 4); // Returns 3.1416
Object¶
object\clear¶
object\clear(OBJECT, KEY): OBJECT
This function unsets a value by a KEY. This function returns a pointer to the same object although it is not required to reference the object.
Example:
$object = object\create();
object\set($object, 'firstName', 'Albert');
object\set($object, 'lastName', 'Einstein');
object\clear($object, 'lastName');
output\printLine($object); // Outputs: {"firstName":"Albert"}
object\cloneDeep¶
object\cloneDeep(OBJECT): OBJECT
This function creates a deep copy of an OBJECT. This function returns a pointer to the same object although it is not required to reference the object.
Example:
$object = object\create();
object\set($object, 'firstName', 'Albert');
object\set($object, 'lastName', 'Einstein');
$results = object\create();
object\set($results, 'Science', 'A');
object\set($results, 'Maths', 'A+');
object\set($results, 'English', 'B');
object\set($object, 'results', $results);
$object2 = object\cloneDeep($object);
$object3 = $object;
object\clear($object, 'lastName');
output\printLine($object);
// Outputs: {"firstName":"Albert","results":{"Science":"A","Maths":"A+","English":"B"}}
output\printLine($object2);
// Outputs: {"firstName":"Albert","lastName":"Einstein","results":{"Science":"A","Maths":"A+","English":"B"}}
output\printLine($object3);
// Outputs: {"firstName":"Albert","results":{"Science":"A","Maths":"A+","English":"B"}}
object\create¶
object\create(): OBJECT
Creates and returns an empty object (key-value map).
Example 1:
$object = object\create();
Example 2:
$object = object\create();
object\set($object, 'firstName', 'Albert');
object\set($object, 'lastName', 'Einstein');
output\printLine($object); // Outputs: {"firstName":"Albert","lastName":"Einstein"}
Example 3:
$object = object\create();
object\set($object, 'firstName', 'Albert');
object\set($object, 'lastName', 'Einstein');
$results = object\create();
object\set($results, 'Science', 'A');
object\set($results, 'Maths', 'A+');
object\set($results, 'English', 'B');
object\set($object, 'results', $results);
output\printLine($object);
// Outputs: {"firstName":"Albert","lastName":"Einstein","results":{"Science":"A","Maths":"A+","English":"B"}}
object\get¶
object\get(OBJECT, KEY): MIXED
This function retrieves a value from an OBJECT using a specified KEY. If the KEY is not set, the function will return NULL.
Example:
$firstName = object\get($object, 'firstName');
Example 2:
$object = object\create();
object\set($object, 'firstName', 'Albert');
object\set($object, 'lastName', 'Einstein');
$firstName = object\get($object, 'firstName');
output\printLine($firstName); // Outputs: "Albert"
object\has¶
object\has(OBJECT, KEY): BOOLEAN
This function determines if a KEY has been assigned a value in an OBJECT and returns a boolean indicating the result.
Example:
$object = object\create();
object\set($object, 'firstName', 'Albert');
object\set($object, 'lastName', 'Einstein');
output\printLine( object\has($object, 'firstName') ); // Outputs true
output\printLine( object\has($object, 'middleName') ); // Outputs false
object\set¶
object\set(OBJECT, KEY, VALUE): OBJECT
This function assigns a value to a KEY. If they KEY does not exist it will be created and assigned the VALUE. This function returns a pointer to the same object, although it is not required to reference the object.
Example 1:
$object = object\create();
object\set($object, 'key', 'some-value');
Example 2:
$object = object\create();
object\set($object, 'firstName', 'Albert');
object\set($object, 'lastName', 'Einstein');
output\printLine($object); // Outputs: {"firstName":"Albert","lastName":"Einstein"}
Output¶
output\print¶
output\print(VALUE): NULL
Prints VALUE without a carriage return/line break.
Special function for use in the Formula Sandbox that is used to print out the value of a variable. This is only displayed output section of the Formula Sandbox.
Examples
output\print('Hello ');
output\print('World'); // Combined these lines will print 'Hello World'
output\printLine¶
output\printLine(VALUE): NULL
Prints VALUE with a carriage return/line break.
Special function for use in the Formula Sandbox that is used to print out the value of a variable. This is only displayed output section of the Formula Sandbox.
Examples
output\printLine('Hello'); // Outputs: 'Hello' + CR/LF
output\printLine('World'); // Outputs: 'World' + CR/LF
Password¶
password\generate¶
password\generate(): STRING
Returns a system generated password.
Example:
$password = password\generate();
output\print($password);
password\hash¶
password\hash(INPUT): STRING
The hash()
function returns a hashed version of the INPUT value. The same input will always generate the same hashed value.
For security reasons and best practice it is important that you only save a hashed version of a password in the password
field of a User
record.
A hash()
function is commonly used for storing passwords in a secure and encrypted form. Instead of storing the actual password, which is considered to be a security risk, a hash function is used to convert the password into a fixed-length string of characters that is unique to the password. The hash function generates this fixed-length string, known as a hash value, by applying a mathematical algorithm to the password.
When a user enters their password to log in, the hash function is applied again to the entered password, and the resulting hash value is compared to the hash value stored in the database. If the two hash values match, it means that the entered password is correct, and the user is granted access. However, if the two hash values do not match, it means that the entered password is incorrect, and the user is denied access.
Hashing passwords is considered to be a best practice in terms of security because it ensures that even if a hacker gains access to the database, they will not be able to retrieve the actual passwords. Instead, they will only be able to see the hash values, which are typically very difficult to reverse engineer. This means that even if a hacker knows the hash value, they cannot use it to log in to the system or access the user's account.
Example:
$password = password\generate(); // Example result: '8jD4nEHI0S'
$hash = password\hash($password); // Returns 'AwDaMjhIxapOxYkDL.RcXVOsSLeor4ylM8qszx.CI5mAqeEkaV84WwxaUBjpbbrCgzMeu7DR0Y6M0qOyrxBQ11'
Record¶
- record\attribute
- record\count
- record\create
- record\exists
- record\findOne
- record\findRelatedOne
- record\findRelatedMany
- record\relate
- record\relationColumn
- record\unrelate
- record\update
- record\updateRelationColumn
record\attribute¶
record\attribute(ENTITY_TYPE, ID, ATTRIBUTE): MIXED
Returns an attribute value of a specific record.
Examples:
record\attribute('Opportunity', $opportunityId, 'amountConverted')
record\attribute('Opportunity', $opportunityId, 'teamsIds')
By utilizing this function along with record\findOne, it's possible to fetch attribute values of any record in the system.
record\count¶
record\count(ENTITY_TYPE, KEY1, VALUE1, [KEY2, VALUE2 ...]): INTEGER
Returns a count of records with specified criteria.
record\count(ENTITY_TYPE, [FILTER]): INTEGER
Returns a count of records with an optional FILTER applied. More info about filters below.
Examples:
record\count('Opportunity', 'accountId=', id, 'stage=', 'Closed Won')
record\count('Opportunity', 'amountConverted>', 1000)
record\count('Opportunity', 'open')
record\count('Lead', 'status=', list('Assigned', 'In Process'))
FILTER is a name of a filter pre-defined in the system.
record\create¶
record\create(ENTITY_TYPE, ATTRIBUTE1, VALUE1, [ATTRIBUTE2, VALUE2 ...]): STRING
Creates a new record of entity type with attributes specified as key-value pairs. Returns id of the created record, or NULL if failure.
Examples:
$id = record\create('Meeting',
'name', 'Sample Meeting',
'dateStart', datetime\today(),
'endStart', datetime\today(),
'status', 'Held',
'assignedUserId', entity\attribute('Id'),
'assignedUserName', entity\attribute('name')
);
Note: To assign the record to User you will need to provide both the
assignedUserId
andassignedUserName
fields.
record\exists¶
record\exists(ENTITY_TYPE, KEY1, VALUE1, [KEY2, VALUE2 ...]): BOOLEAN
Check whether a record with specified criteria exists and returns a corresponding boolean value.
Examples:
record\exists('Lead', 'emailAddress=', fromAddress)
record\exists('Lead', 'status=', list('Assigned', 'In Process'))
record\findOne¶
record\findOne(ENTITY_TYPE, ORDER_BY, ORDER, [KEY1, VALUE1, KEY2, VALUE2 ...]): STRING
Returns a first found ID of a record that matches specific criteria.
record\findOne(ENTITY_TYPE, ORDER_BY, ORDER, [FILTER]): STRING
Returns a first found ID of a record with an optional FILTER applied.
Examples:
record\findOne('Opportunity', 'createdAt', 'desc', 'accountId=', id, 'stage=', 'Closed Won')
record\findOne('Opportunity', 'createdAt', 'desc', 'open')
FILTER is a name of a filter pre-defined in the system.
record\findRelatedOne¶
record\findRelatedOne(ENTITY_TYPE, ID, LINK, [ORDER_BY, ORDER, KEY1, VALUE1, KEY2, VALUE2 ...]): STRING
Returns a first found ID of a related record that matches specific criteria.
record\findRelatedOne(ENTITY_TYPE, ID, LINK, [ORDER_BY, ORDER, FILTER]): STRING
Returns a first found ID of a related record with an optional FILTER applied.
If NULL is passed for ORDER_BY and ORDER then a default order will be applied.
Examples:
record\findRelatedOne('Account', accountId, 'opportunities', 'createdAt', 'desc', 'stage=', 'Closed Won')
record\findRelatedOne('Account', accountId, 'opportunities', 'createdAt', 'desc', 'open')
FILTER is a name of a filter pre-defined in the system.
record\findRelatedMany¶
record\findRelatedMany(ENTITY_TYPE, ID, LINK, LIMIT, [ORDER_BY, ORDER, KEY1, VALUE1, KEY2, VALUE2 ...]): STRING[]
Returns an array of IDs of a related record that matches specific criteria. LIMIT is the max number of record.
record\findRelatedMany(ENTITY_TYPE, ID, LINK, LIMIT, [ORDER_BY, ORDER, FILTER]): STRING[]
Returns an array of IDs of a related record with an optional FILTER applied.
If NULL is passed for ORDER_BY and ORDER then a default order will be applied.
Examples:
record\findRelatedMany('Account', accountId, 'oppotunities', 10, 'createdAt', 'desc', 'stage=', 'Closed Won')
record\findRelatedOne('Account', accountId, 'oppotunities', 3, 'createdAt', 'desc', 'open')
FILTER is a name of a filter pre-defined in the system.
This function can be utilised for copying related records from one record to another. Example:
// copy teams from account to email
$ids = record\findRelatedMany('Account', $accountId, 'teams', 10);
record\relate('Email', $emailId, 'teams', $ids);
record\relate¶
record\relate(ENTITY_TYPE, ID, LINK, FOREIGN_ID): NULL
Relates two records.
record\relate(ENTITY_TYPE, ID, LINK, LIST_OF_IDS): NULL
Links a record with multiple records.
Examples:
record\relate('Account', $accountId, 'opportunities', $opportunityId)
record\relate('Account', $accountId, 'tasks', list('id1', 'id2'))
Note: If a new record is being created, the formula cannot be processed in the Before save script because the record does not exist yet.
record\relationColumn¶
record\relationColumn(ENTITY_TYPE, ID, LINK, FOREIGN_ID, COLUMN): MIXED
Returns a relation column.
Example:
record\relationColumn('Account', $accountId, 'contacts', $contactId, 'role')
Example (condition checking position in team):
record\relationColumn('User', $someUserId, 'teams', 'some-team-id, 'role') == 'Support Manager'
record\unrelate¶
record\unrelate(ENTITY_TYPE, ID, LINK, FOREIGN_ID): NULL
Unlinks two records.
Example:
record\unrelate('Account', $accountId, 'opportunities', $opportunityId)
record\update¶
record\update(ENTITY_TYPE, ID, ATTRIBUTE1, VALUE1, [ATTRIBUTE2, VALUE2 ...])
Updates an existing record with attributes specified as key-value pairs. Returns TRUE if success, FALSE if failure.
Examples:
record\update('Meeting', 'SOME-MEETING-ID', 'emailAddress', 'SOME@ADDRESS.com', 'assignedUserId', 'SOME-USER-ID')
It will update the meeting with ID SOME-MEETING-ID
, and will set emailAddress = 'SOME@ADDRESS.com'
, assignedUserId = 'SOME-USER-ID'
.
record\updateRelationColumn¶
record\updateRelationColumn(ENTITY_TYPE, ID, LINK, FOREIGN_ID, COLUMN, VALUE): NULL
Updates a relation column.
Example:
record\updateRelationColumn('Account', $accountId, 'contacts', $contactId, 'role', 'CEO')
String¶
- string\concatenate
- string\contains
- string\length
- string\lowerCase
- string\match
- string\matchAll
- string\pad
- string\pos
- string\replace
- string\split
- string\substring
- string\test
- string\trim
- string\upperCase
string\concatenate¶
string\concatenate(STRING_1, STRING_2): STRING
Concatenates two or more strings.
Examples:
$someVariable = string\concatenate('ab', 'cd'); // Returns 'abcd'
$someVariable = string\concatenate('ab', 'cd', 'ef'); // Returns 'abcdef'
string\contains¶
string\contains(STRING, NEEDLE): BOOLEAN
Whether STRING contains NEEDLE.
Example:
string\contains('hello world', 'world') // will return true
string\length¶
string\length(STRING): INTEGER
The length of STRING.
Example:
string\length('hello world') // will return `11`
string\lowerCase¶
string\lowerCase(STRING): STRING
Converts letters to lower case.
Example:
string\lowerCase('HELLO world') // will return `hello world`
string\match¶
string\match(STRING, REGULAR_EXPRESSION, [OFFSET]): STRING|NULL
Retrieves the first result of matching a STRING against a REGULAR_EXPRESSION. Returns NULL if no matches are found.
Example:
string\match('{token1} foo {token2} bar', '/{[^}]*}/')
will return {token1}
.
The slash character /
defines the start and the end of a REGULAR_EXPRESSION.
string\matchAll¶
string\matchAll(STRING, REGULAR_EXPRESSION, [OFFSET]): STRING|NULL
Retrieves all results of matching a STRING against a REGULAR_EXPRESSION. Returns NULL if no matches are found.
Example:
string\matchAll('{token1} foo {token2} bar', '/{[^}]*}/')
will return an array ['{token1}', '{token2}']
.
string\pad¶
string\pad(STRING, LENGTH, [PAD_STRING], [PAD_TYPE]): STRING
Pads STRING to a certain LENGTH with PAD_STRING.
PAD_STRING by default is a whitespace string ' '
.
PAD_TYPE can be 'right', 'left', 'both'. By default it is 'right'.
Example:
string\pad('100', 5, '*', 'right') // will return `100**`
string\pos¶
string\pos(STRING, NEEDLE): INTEGER
Returns possition of NEEDLE in STRING, false if not found.
Example:
string\pos('hello world', 'world') // will return `6`
string\replace¶
string\replace(STRING, SEARCH, REPLACE): STRING
Replaces all occurrences of SEARCH with REPLACE in STRING.
Example:
string\replace('Hello {test}', '{test}', 'world')
will return 'Hello world'
.
string\split¶
string\split(STRING, SEPARATOR): STRING[]
This function takes a STRING and a SEPARATOR as inputs, and splits the STRING into an array of strings based on the SEPARATOR.
Example:
string\split('hello world', ' ') // will return ['hello', 'world']
string\substring¶
string\substring(STRING, START, LENGTH): STRING
Extracts the characters from a STRING by START position and LENGTH.
If LENGTH is omitted, the substring starting from START until the end of the STRING will be returned.
If LENGTH is negative, then that many characters will be omitted from the end of STRING.
Examples:
$someVariable = string\substring('abcde', 1, 2); // will return 'bc'
$someVariable = string\substring('abcde', 1, -1); // will return 'bcd'
string\test¶
string\test(STRING, REGULAR_EXPRESSION): BOOLEAN
Search a match between REGULAR_EXPRESSION and STRING. Returns TRUE of FALSE.
Example:
string\test('hello world', '/hello/i') // will return TRUE
string\trim¶
string\trim(STRING): STRING
Strips whitespace from the beginning and end of STRING.
Example:
string\trim(' hello world ') // will return `hello world`
string\upperCase¶
string\upperCase(STRING): STRING
Converts letters to upper case.
Example:
string\upperCase('HELLO world') // will return `HELLO WROLD`
Util¶
Application Utilities
Business Hours Utilities
Push Notification Utilities
Application Utilities
util\generateId¶
util\generateId(): STRING
Generates a unique ID. Returns a string.
Example:
$uniqueId = util\generateId();
util\getApplicationParam¶
util\getApplicationParam(param type): STRING
Returns Application Parameters as a string.
Possible Parameters types are:
- ApplicationName
- ApplicationUrl
Example:
$appName = util\getApplicationParam('ApplicationName');
$appURL = util\getApplicationParam('ApplicationUrl');
Business Hours
util\businessHoursAddHours¶
util\businessHoursAddHours(businessHourMythId, initialTime, hoursToAdd): DATETIME
The businessHoursAddHours()
function is used to add Business Hours to an existing date/time value.
For example if you need to add 14 business hours to a date/time value that is on a Friday afternoon and your standard business hours do not include weekends, then the new date/time value would probably be sometime on the following Tuesday. This function will calculate that new date/time based on the Business Hours used in the calculation. This function can be used to add a number of Business Hours to the passed in date/time by simply using a positive or negative value in the hourToAdd parameter.
Returns a Datetime.
Parameters
Parameter | Description |
---|---|
businessHourMythId | Unique row id of a Business Hours record that you wish to use for calculating the time between the start and end dates |
initialTime | Initial date/time value that you wish to add to the Business Hours |
hoursToAdd | Number of Business Hours to add to the initialTime value |
util\businessHoursCalcHours¶
util\businessHoursCalcHours(businessHourMythId, startTime, endTime): FLOAT
The businessHoursCalcHours()
function is used to calculate the number of Business Hours between one date/time value and a second date/time value.
Returns a float.
Parameters
Parameter | Description |
---|---|
businessHourMythId | Unique row id of a Business Hours record that you wish to use for calculating the time between the start and end dates. |
startTime | Start Date/Time value. |
endTime | End Date/Time value. |
Push Notification Utilities
Mythradon supports the following three functions for sending Push Notifications:
- util\SendNotificationToUser - Sends a Push Notification to a specific User identified by their Id value (Unique row id of a User record)
- util\SendNotificationToTeam - Sends a Push Notification to all the members of a specific Team identified by the Team Id (Unique row id of a Team record)
- util\SendNotificationToTeamsOnRecord - Sends a Push Notification to all the members of all the Teams associated to entity id the formula is being used on
Note: The Send Notification functions support a set of Name/Value pair parameters known as 'OPTION_NAME'/'OPTION_VALUE'. The only parameter that is currently supported is 'url'. However, Mythradon intends to expand these functions in the future.
util\SendNotificationToUser¶
util\SendNotificationToUser(USER_ID, TITLE, MESSAGE, OPTION_NAME1, OPTION_VAL1, OPTION_NAME.., OPTION_VAL..): NULL
The SendNotificationToUser()
function will send a Push Notification to a specific User.
Parameters
Parameter | Description |
---|---|
USER_ID | Unique row id of a User record that you wish to send the Push Notification to. |
TITLE | Title in the Push Notification message. |
MESSAGE | Body of the Push Notification message. |
OPTION_NAME | First name of the name/value pair parameters. Only value currently supported is 'url'. |
OPTION_VAL | First value of the name/value pair parameters. Only value currently supported is a valid url that will be a link in the Push Notification. |
Sample
$url = string\concatenate(util\getApplicationParam('ApplicationUrl'), '/#Case/view/', id);
util\SendNotificationToUser(id, 'Hello World', 'That/'s one small step for man, one giant leap for mankind.', 'url', 'https://airandspace.si.edu/stories/editorial/one-small-step-man-or-man');
Note: The Send Notification functions support a set of Name/Value pair parameters known as 'OPTION_NAME'/'OPTION_VALUE'. The only parameter that is currently supported is 'url'. However, Mythradon intends to expand these functions in the future.
util\SendNotificationToTeam¶
util\SendNotificationToTeam(TEAM_ID, TITLE, MESSAGE, OPTION_NAME1, OPTION_VAL1, OPTION_NAME.., OPTION_VAL..): NULL
The SendNotificationToTeam()
function will send a Push Notification to all the members of a specific Team identified by the Team Id (Unique row id of a Team record).
Parameters
Parameter | Description |
---|---|
TEAM_ID | Unique row id of a Team record that you wish to send the Push Notification to. |
TITLE | Title in the Push Notification message. |
MESSAGE | Body of the Push Notification message. |
OPTION_NAME | First name of the name/value pair parameters. Only value currently supported is 'url'. |
OPTION_VAL | First value of the name/value pair parameters. Only value currently supported is a valid url that will be a link in the Push Notification. |
Sample
$url = string\concatenate(util\getApplicationParam('ApplicationUrl'), '/#Case/view/', id);
util\SendNotificationToTeam(teamsIds, 'Hello World', 'That/'s one small step for man, one giant leap for mankind.', 'url', 'https://airandspace.si.edu/stories/editorial/one-small-step-man-or-man');
util\SendNotificationToTeamsOnRecord¶
util\SendNotificationToTeamsOnRecord(ENTITY_ID, ENTITY_TYPE, TITLE, MESSAGE, OPTION_NAME1, OPTION_VAL1, OPTION_NAME.., OPTION_VAL..): NULL
The SendNotificationToTeamsOnRecord()
function will send a Push Notification to all the members of all the teams that are associated to a record.
Mythradon supports the ability to assign more than one teams to a record. Teams are used in conjunction with Roles to control visibility to records. Mythradon also allows for a User to be a memeber of many teams.
The sendNotificationToTeamsOnRecord()
function allows you to send a Push Notification all all members of all teams. If a User is a member of more than one Team that is assigned to the record, they will only receive a single Push Notification message.
Parameters
Parameter | Description |
---|---|
ENTITY_ID | Unique row id of an Entity that you want to send a Push Notificication all the related Team members. |
TITLE | Title in the Push Notification message. |
MESSAGE | Body of the Push Notification message. |
OPTION_NAME | First name of the name/value pair parameters. Only value currently supported is 'url'. |
OPTION_VAL | First value of the name/value pair parameters. Only value currently supported is a valid url that will be a link in the Push Notification. |
Sample
ifThen(
entity\isNew(),
$url = string\concatenate(util\getApplicationParam('ApplicationUrl'), '/#Case/view/', id);
util\SendNotificationToTeam('5f137834ed903a606', 'New Case Created', 'A new case has been created', 'url', $url);
);
Values¶
- Strings. E.g. 'some string';
- Integer numbers. E.g. 1, 100, 40300.
- Float numbers. E.g. 5.2.
Variables¶
It's possible to define custom variables in formula.
$someVariableName = 'Test';
description = $test;
Comments¶
Line comment:
// comment
Section comment:
/*
comment
*/
Function arguments¶
LINK¶
A name of the relationship. Available link names can be found at Administration > Entity Manager > ... > Relationships.
Link names must be wrapped in quotes when used as function arguments.
More info about links here.
ATTRIBUTE¶
Attribute name usually is the same as a system field name. Fields are listed in Entity Manager > ... > Fields.
Field types having multiple attributes:
- Link: fieldId, fieldName.
- Link-Multiple: fieldIds, fieldNames.
- Link-Parent: fieldId, fieldType, fieldName.
- Currency: field, fieldCurrency.
Where field is the name of the field.
Attribute names must be wrapped in quotes when used as function arguments. E.g. record\attribute('Lead', 'someId', 'assignedUserId')
.
More info about attributes here.
ENTITY_TYPE¶
ENTITY_TYPE list is available at Administration > Entity Manager.
Entity type names must be wrapped in quotes when used as function arguments. E.g. record\attribute('Lead', 'someId', 'assignedUserId')
.
More info about entity types here.
FILTER¶
A name of a filter pre-defined in the system.
Comparison¶
The following comparison operators are available:
==
- equals,!=
- not equals,>
- greater than,<
- less than,>=
- greater than or equals,<=
- less than or equals.
Important: Strict comparison is used. If you compare int 1
to float 1.0
with ==
operator they are treated as not equal. You need to compare values of same types or check whether a value falls in range with $a - 0.0001 <= $b && $b <= $a + 0.0001
.
Examples¶
// Set the 'Assigned User Id' and 'Status' fields if the record is newly created and the 'Assigned User Id' has not been set
ifThen(
entity\isNew() && assignedUserId == null,
assignedUserId = 'managerId';
status = 'Assigned';
);
// Set the value of the 'someDateField' to todays date if the record is newly created and 'closeDate' is not set and 'stage' equals 'Closed Won'
someDateField = ifThen(entity\isNew() && closeDate == null && stage == 'Closed Won',
datetime\today()
);
amount = product.listPrice - (product.listPriceConverted * discount / 100.0);
amountCurrency = 'USD';
someField = string\concatenate(firstName, " '", middleName, "' ", lastName);
ifThenElse(entity\isNew() && status == 'Planned' && dateStart == null,
dateStart = datetime\addDays(datetime\now(), 10),
ifThen(status == 'Held' && dateStart == null,
dateStart = datetime\now()
)
);
Explanation¶
Functions accept expressions as arguments.
someFunction(EXPRESSION1, EXPRESSION2);
EXPRESSION1 can be:
- scalar value
- variable
- attribute
- combination of all those forming an expression
Scalar STRING as an argument:
someFunction('some string');
Scalar INT as an argument:
someFunction(10);
Scalar FLOAT as an argument:
someFunction(10.5);
Scalar BOOLEAN as an argument:
someFunction(true);
NULL value as an argument:
someFunction(null);
Expression as an argument:
someFunction(2 + 2);
Expression as an argument:
someFunction(anotherFunction());
Variable as an argument:
someFunction($someVariable);
Attribute as an argument:
someFunction(attributeName);
See also¶
- Mythradon Basics
- Mythradon Marketing
- Mythradon Sales
- Mythradon Service
- Mythradon System Administration
- Mythradon Tools