Examples - JavaScript in Lucernex
This topic provides examples of how JavaScript can be used in Lucernex and useful functions that you may want to utilize.
Generic Examples
The following expanding sections provide generic examples of how JavaScript can be used in Lucernex.
These scripts use sample field names, some of which may not exist in your firm. Replace field names with your target field names as needed. To learn proper field name syntax, see our Syntax article.
Conditional Work Flow Examples
You can kick off several work flows from the same kickoff form, depending on which action the user selects. You can also specify under what circumstances a work flow should be kicked off if a scheduled task is completed. This functionality is configured by adding custom JavaScript to the work flow. Learn more about this functionality.
Example 1: Only kick off work flow if a certain condition is true
In this example, the JavaScript will enable the work flow if the store number is equal to 12345.
1
2
3
4
5
6
var ActionEnabled = false;
var storeNumber = "${ProjectEntity.StoreNumber}";
if (storeNumber == "12345")
{
ActionEnabled = true;
}
Example 2: Only kick off Change Order or Payment Application work flow if Purchase Order field meets certain condition
In this example, the JavaScript will enable the work flow if the related Purchase Order's VendorPONumber contains the value ABC. You can reference any field on a purchase order, and the system will understand the relationship between the purchase order and the change order or payment application.
1
2
3
4
5
var ActionEnabled = “false”;
var po = “${PurchaseOrder.VendorPONumber}”;
if (po.indexOf(“ABC”) > -1) {
ActionEnabled = “True”
}
Manage Data Field Example
Description
This script is intended to populate a Site's Name field (ProjectEntityName). The script uses the store number, city, state, and deal status. You would use this script to enforce entity naming conventions and to avoid duplicate data entry. This script could also be used on a page or form. Please see the Introduction for differences in application.
This is a very basic script that does not check whether the source fields are populated.
Example
1
2
3
4
5
6
7
// Produces a concatenated string from the input fields.
var valueToSet = "";
var storeNum = "${ProjectEntity.ClientEntityID}";
var city = "${ProjectEntity.City}";
var state = "${ProjectEntity.IStateProvinceCountryID}";
var dealStatus = "${ProjectEntity.DealStatus}";
valueToSet = storeNum + " – " + city + " – " + state + " – " + dealStatus;
Report Example
Description
This script is useful in scenarios where you want to restrict your report to records that fall within a time period of one date relative to another; for example, all key date records whose notice end date is within the next 30 days. While you can do this with standard runtime filters, runtime filters cannot be applied to scheduled reports.
The other context where this useful is when you need to calculate the number of days between two dates. Date math built into the Report Builder interprets the difference between two dates into a string, such as "6 months, 7 days". Date math in Lucernex uses contract date math, which follows the formula end date - start date + 1. This formula is used so that you can treat the difference between the dates as a number.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Get the number of days between two dates.
// If date1 is before date2, value will be positive.
// If date1 is after date2, value will be negative.
var valueToSet = "";
var dateStr1 = "${TableName.DateFieldName1}";
var dateStr2 = "${TableName.DateFieldName2}";
if (dateStr1.length != 0 && dateStr2.length != 0) {
var date1 = new Date(dateStr1);
var date2 = new Date(dateStr2);
var MILLI_SECS_PER_DAY = 86400000;
var timeDiff = date2.getTime() - date1.getTime(); // In milliseconds
valueToSet = timeDiff / MILLI_SECS_PER_DAY; // In days
}
Work Flow Example
Description
You can use JavaScript to make work flow approval actions appear only when certain conditions are met. A common use of this type of JavaScript is to set up approval thresholds for requisitions, change orders, and invoices. The script below is designed to display on an approval action in a change order work flow. The script will ensure that this action is only available if the project is a remodel and the change amount is greater than or equal to $5,000.
Example
1
2
3
4
5
6
7
8
9
// Makes the approval action unavailable unless total is
// greater than or equal to 5000 AND projType is "Remodel"
var ActionEnabled = false;
var total = "${Issue.TotalChangeAmount}";
var projType = "${ProjectEntity.CodeProjectTypeID}";
if (total >= 5000 && projType == "Remodel") {
ActionEnabled = true;
}
Complex Examples
This section contains complex JavaScript that can be used in Lucernex. Each expanding section contains a script and an explanation of what the script does.
These scripts use sample field names, some of which may not exist in your firm. Replace field names with your target field names as needed. To learn proper field name syntax, see our Syntax article.
Date Math: Date + Number of Days
This script gets the value of a date field and adds the value of a number field to the date. The resulting value is another date.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Add a number to a date and return the new date.
var valueToSet = "";
var dateStr = "${TableName.DateFieldName}";
var numToAdd = getNum("${TableName.NumFieldName}");
if (dateStr.length != 0) {
var date = new Date(dateStr);
var MILLI_SECS_PER_DAY = 86400000;
var newTime = date.getTime() + (MILLI_SECS_PER_DAY * numToAdd); // In milliseconds
var newDate = new Date(newTime); // As a Date object
valueToSet = formatDate(newDate);
}
///////////////////// FUNCTIONS /////////////////////
/*
* Take a variable of any type and return a number.
* If it is a number, return it as a number.
* If it can be represented as a number by removing non-numeric characters, return it as a number.
* Otherwise, return 0.
*/
function getNum(n) {
if (n instanceof Number){ // if already a number, return it
return n;
}
try {
if (isNaN(n)){ // if not a valid number
n = "" + n; // make sure n is a string
n = n.replace(/\%|,|\$/gi, ""); // get rid of non-numeric chars
}
if (!isNaN(n)){ // if n is a valid number, return it
return Number(n);
}
} catch(e){} // do nothing if there’s an error
return Number(0); // always return 0 if we get to this point.
}
// Takes a Date variable.
// Returns a String in MM/dd/yyyy format.
function formatDate(date) {
return getTwoCharForInt(date.getMonth() + 1) + "/" +
getTwoCharForInt(date.getDate()) + "/" + date.getFullYear();
}
function getTwoCharForInt(int) {
return int < 10 ? "0" + int : "" + int;
}
Date Math: Calculate the number of days between two dates
This script calculates the number of days between two dates. You can adapt this script to calculate weeks, months, years, and so on.
This script calculates the difference, not the duration. If you want to calculate the duration between two dates—including those dates—change line 13 (valueToSet = timeDiff / MILLI_SECS_PER_DAY; // In days) to valueToSet = (timeDiff / MILLI_SECS_PER_DAY) + 1; // Duration in days.
If you are using this script on a date field that includes a time component, such as CreatedDate or ModifiedDate, consider either clearing the time component or rounding to the next date.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// If date1 is before date2, value will be positive.
// If date1 is after date2, value will be negative.
var valueToSet = "";
var dateStr1 = "${TableName.DateFieldName1}";
var dateStr2 = "${TableName.DateFieldName2}";
if (dateStr1.length != 0 && dateStr2.length != 0) {
var date1 = new Date(dateStr1);
var date2 = new Date(dateStr2);
var MILLI_SECS_PER_DAY = 86400000;
var timeDiff = date2.getTime() - date1.getTime(); // In milliseconds
valueToSet = timeDiff / MILLI_SECS_PER_DAY; // In days
}
Date Validation: Is this date the 1st date of the month?
This script gets the value of a date field and validates whether the date is the first day of the month. It returns a true or false value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Is date first day of month?
var valueToSet = false;
var dateStr = "${TableName.FieldName}";
if (dateStr.length != 0) {
var originalDate = new Date(dateStr);
var firstDayOfMonth = new Date(dateStr);
firstDayOfMonth.setDate(1);
if (originalDate.getTime() == firstDayOfMonth.getTime()) {
valueToSet = true;
}
}
Date Validation: Is this date the last day of the month?
This script gets the value of a date field and validates whether the date is the last day of the month. It returns a true or false value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Is date last day of month?
var valueToSet = false;
var dateStr = "${TableName.FieldName}";
if (dateStr.length != 0) {
var originalDate = new Date(dateStr);
var lastDayOfMonth = new Date(dateStr);
// Set date to mid-month to avoid rolling moving forward two months if date is > 28.
lastDayOfMonth.setDate(15);
// Go to next month.
// If it's December, the integer will be 12, but will still set the date to January.
lastDayOfMonth.setMonth(lastDayOfMonth.getMonth() + 1);
// Setting the date to zero goes to the last day of the previous month.
lastDayOfMonth.setDate(0);
if (originalDate.getTime() == lastDayOfMonth.getTime()) {
valueToSet = true;
}
}
Date Validation: is today within the target date range?
This script gets today's date and validates whether today's date falls between the values of two date fields. This script returns either a true or false value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Is today within the target date range?
// Begin Date is specified
// AND End Date is specified
// AND Begin Date <= Today <= End Date.
var valueToSet = false;
var beginStr = "${ExpenseSchedule.BeginDate}";
var endStr = "${ExpenseSchedule.EndDate}";
var today = clearTime(new Date()); // Requires clearTime function.
if (beginStr.length != 0 && endStr.length != 0) {
var beginDate = new Date(beginStr);
var endDate = new Date(endStr);
if (beginDate.getTime() <= today.getTime() && today.getTime() <= endDate.getTime()) {
valueToSet = true;
}
}
///////////////////// FUNCTIONS /////////////////////
// Function to clear time component.
function clearTime(Date date) {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
Date Validation: is today within a partially open date range?
This script gets today's date and validates whether today's date meets one of the following conditions:
-
If the Begin Date is not specified, the End Date is specified AND Today is less than or equal to the End Date.
-
If the End Date is not specified, the Begin Date is specified AND the Begin Date is less than or equal to Today.
-
If the Begin Date and End Date are specified, the Begin Date is less than or equal to Today, AND Today is less than or equal to the End Date.
This script returns either a true or false value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Is today within partially open date range?
// If Begin Date is not specified, End Date is specified AND Today <= End Date.
// If End Date is not specified, Begin Date is specified AND Begin Date <= Today.
// If Begin Date and End Date are specified, Begin Date <= Today <= End Date.
var valueToSet = false;
var beginStr = "${ExpenseSchedule.BeginDate}";
var endStr = "${ExpenseSchedule.EndDate}";
var today = clearTime(new Date()); // Requires clearTime function.
if (beginStr.length != 0 || endStr.length != 0) {
var MILLI_SECS_PER_DAY = 86400000;
if (beginStr.length == 0) {
// Only end is specified. Is today before/on End Date?
var endDate = new Date(endStr);
if (today.getTime() <= endDate.getTime()) {
valueToSet = true;
}
} else if (endStr.length == 0) {
// Only begin is specified. Is Begin Date before/on today?
var beginDate = new Date(beginStr);
if (beginDate.getTime() <= today.getTime()) {
valueToSet = true;
}
} else {
// Both are specified. Is Begin Date before/on today and today before/on End Date?
var beginDate = new Date(beginStr);
var endDate = new Date(endStr);
if (beginDate.getTime() <= today.getTime() && today.getTime() <= endDate.getTime()) {
valueToSet = true;
}
}
}
///////////////////// FUNCTIONS /////////////////////
// Function to clear time component.
function clearTime(Date date) {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
Create a that Opens a Link in a new Window / Tab
This is a simple script that can be used to create a static hyperlinked to a website outside of Lucernex. When the user clicks the button, the link will open in a new window or tab based upon their browser settings. In Lucernex, links are always opened in the same window or tab. This script allows you to override this global setting so that the user can continue to have Lucernex open in another browser instance.
This script can be modified to create dynamic links that depend on the record the instance of the field is tied to. Common applications that leverage Lucernex entity data include:
-
link to a mapping system
By pulling the latitude and longitude from a location, we can open the mapping system and zoom to the location on the map.
-
link to a document management system
By using unique entity-level identifiers, we can open a sub-folder related to a specific entity in a document management system.
-
link to a point of sale (POS) system
By using unique entity-level identifiers, we can open entity-specific sales data in your POS system.
1
2
3
4
5
6
7
8
9
10
11
12
13
// Creates a that goes to the specified link in a new window/tab.
var valueToSet = "";
var label = "Google";
var url = "https://www.google.com";
valueToSet = "<FORM><BR />" +
"<INPUT type=\"button\" " +
"value=\""+ label + "\" " +
"onclick=\"window.open('" + url + "')\"/>" +
"<BR />" +
"</FORM>";
Stoplight Status Indicator Fields
This script is typically used by clients to indicate the status of projects in their portfolio, but this could be used for other entity types or with other fields.
This script utilizes two fields that are added to a page layout. In Edit mode, the user selects a value from a drop-down field. After the page has been saved, this script creates a colored shape that is displayed in View mode based upon the selected value. The color and size of the indicator can be configured, and the client can create a square, rectangle, circle, or oval indicator based upon the proportions and characteristics they choose for the shape.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* INSTRUCTIONS
* 1. Create two fields on the same table: One dropdown for users to edit. One text field to hold the JavaScript.
* 2. Replace the field name in the curly braces below with the script name of the editable dropdown field you created.
* 3. Update the status values in the STATUS SETTINGS section.
* 4. Add the JavaScript to the text field in the Manage Data Fields area.
* 5. Add both fields to the same layout with the following settings:
* - Dropdown = Hide in view mode
* - Text = Read only, hide label, hide in all non-view modes
* 6. Try it out on the page!
* 7. Play with the SHAPE SETTINGS and COLOR SETTINGS to get the look you want.
*/
// Display status as solid-colored shape (circle or rectangle).
var valueToSet = "";
var status = "${ProjectEntity.UDF_StoplightStatusEdit}"; // TODO: Update field inside curly braces.
var color = null;
////////////// STATUS SETTINGS //////////////
var redStatus = "Serious Risk";
var yellowStatus = "Some Risk";
var greenStatus = "On Track";
var blueStatus = "Complete";
var grayStatus = "Cancelled";
////////////// SHAPE SETTINGS //////////////
var showCircle = true;
var height = 50;
var width = 50;
////////////// COLOR SETTINGS //////////////
// For a list of HTML color names, go to https://www.w3schools.com/colors/colors_names.asp
var redColor = "red";
var yellowColor = "yellow";
var greenColor = "lightgreen";
var blueColor = "blue";
var grayColor = "lightgray";
////////////// ACTUAL CODE //////////////
switch(status) {
case redStatus: {
color = redColor;
break;
}
case yellowStatus: {
color = yellowColor;
break;
}
case greenStatus: {
color = greenColor;
break;
}
case blueStatus: {
color = blueColor;
break;
}
case grayStatus: {
color = grayColor;
break;
}
}
if (color != null) {
valueToSet = "<table><tr><td style='" +
"color:" + color + ";" +
(showCircle ? "border-radius:50%;" : "") +
"background-color:" + color + ";" +
"height:" + height + "px;" +
"width:" + width + "px;" +
"'>" + status + "</td></tr></table>";
}