Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Please review my client script

Dash2
ServiceNow Employee
ServiceNow Employee

Hello, community,

 

I'm trying to set up an onLoad script that displays a message on the record when the asset end of life date is three months or less away from today.

 

I'm using a combination of g_scratchpad to get the date, and then calling it from the client script, but to no avail.

 

Business rule:

g_scratchpad.eoul = current.cmn_end_of_useful_life;

 

Client script

var eoul = g_scratchpad.eoul;

    function isThreeMonthsFromDate(eoul) {
        var gdt = new GlideDateTime(eoul); // Convert the input date to GlideDateTime

        // Add three months to the input date
        gdt.addMonthsLocalTime(3);

        // Get today's date
        var today = new GlideDateTime();

        // Check if the resulting date matches today's date
        if (gdt.getYear() === today.getYear() &&
            gdt.getMonth() === today.getMonth() &&
            gdt.getDayOfMonth() === today.getDayOfMonth()) {
            g_form.addInfoMessage("This asset is three months away from the end of its useful life. Please refrain from assigning it to an employee as a primary work device.");

        }
    }

@Ankur Bawiskar 

4 REPLIES 4

MackI
Kilo Sage

hi @Dash2 

 

Please see the Client Script  code below , I am assuming this is for the ITAM Module ---

 

 

function onLoad() {
    // Ensure the 'End of Useful Life' field exists on the form
    if (g_form.hasField('cmn_end_of_useful_life')) { 

        // Get the End of Useful Life date in a standardized format
        var eolDate = g_form.getValue('cmn_end_of_useful_life');  
        var gdtEol = new GlideDateTime(eolDate); 

        // Calculate the date three months from today
        var threeMonthsFromToday = new GlideDateTime();
        threeMonthsFromToday.addMonthsLocalTime(3);
        
        // Check if the EOL is within the next three months
        if (gdtEol.compareTo(threeMonthsFromToday) <= 0) {
            // EOL is within three months, display the message
            g_form.addInfoMessage("This asset is three months or less away from the end of its useful life. Please refrain from assigning it to an employee as a primary work device.");
        }
    }
}

 

Explanation of Changes and Improvements:
1. Direct Field Retrieval: The script now directly gets the end-of-life date (eolDate) from the form field cmn_end_of_useful_life using g_form.getValue(). This eliminates the need for the business rule and g_scratchpad.
2. Date Handling:
* new GlideDateTime(eolDate) ensures that the retrieved eolDate is converted into a GlideDateTime object for accurate date comparisons.
* threeMonthsFromToday is calculated by adding 3 months to the current date.
3. Date Comparison:
* The compareTo() method is used to compare the eolDate with threeMonthsFromToday.
* gdtEol.compareTo(threeMonthsFromToday) <= 0 checks if the eolDate is today or earlier than threeMonthsFromToday. This covers the case where the EOL is exactly three months away.
4. Field Existence Check: The script now includes a check (g_form.hasField('cmn_end_of_useful_life')) to ensure that the required field actually exists on the form. This prevents errors if the script runs on a different form.
5. Message Clarity: The message is modified to clearly indicate that the asset is "three months or less" away from the end of its useful life.
Key Points:
* onLoad Client Script: Make sure this script is attached to the "onLoad" event of the client script in your ITAM module's asset form.
* Field Name: Double-check that the field name (cmn_end_of_useful_life) matches the actual field name in your instance.
* Customization: You can easily adjust the time frame (e.g., one month, six months) by modifying the addMonthsLocalTime(3) part.
* Error Handling: Consider adding additional error handling, such as checking if eolDate is a valid date before creating the GlideDateTime object.

 

If you like this solution. Please kindly mark this as your best answer and help to contribute more to this community

 

MackI | ServiceNow Technical Consultant | DXC Technology Australia | ServiceNow Practice | LinkedIn Top IT Operation Voice 2023 | Sydney,Australia

Prashanth Reddy
Tera Expert

hi @Dash2 

 

You should pass string to the scratchpad object. Please use the below code 

 

Business Rule:

(function executeRule(current, previous /*null when async*/) {
// Ensure the date field exists and is populated
if (current.cmn_end_of_useful_life) {
g_scratchpad.eoul = current.cmn_end_of_useful_life.getDisplayValue();
}
})(current, previous);

 

 

Client Script:

 

function onLoad() {
var eoul = g_scratchpad.eoul;

if (eoul) {
isThreeMonthsFromDate(eoul);
}
}

function isThreeMonthsFromDate(eoulDate) {
var gdt = new GlideDateTime(eoulDate); // Convert the input date to GlideDateTime

// Get today's date
var today = new GlideDateTime();

// Calculate the date three months from today
var threeMonthsFromToday = new GlideDateTime(today);
threeMonthsFromToday.addMonthsLocalTime(3);

// Compare the end of useful life date with today's date
if (gdt <= threeMonthsFromToday && gdt >= today) {
g_form.addInfoMessage("This asset is three months or less away from the end of its useful life. Please refrain from assigning it to an employee as a primary work device.");
}
}

onLoad();

 

 

If you like this solution. Please kindly mark this as your best answer and help to contribute more to this community

 

Ankur Bawiskar
Tera Patron
Tera Patron

@Dash2 

couple of issues in your client script -> GlideDateTime is server side and won't work in client side

update as this

Business rule

g_scratchpad.eoul = 'false';

var eolDate = current.getValue('cmn_end_of_useful_life');
var gdtEol = new GlideDateTime(eolDate);

// Calculate the date three months from today
var threeMonthsFromToday = new GlideDateTime();
threeMonthsFromToday.addMonthsLocalTim(3);

// Check if the EOL is within the next three months
if (gdtEol.compareTo(threeMonthsFromToday) <= 0) {
    g_scratchpad.eoul = 'true';
}

client script

if(g_scratchpad.eoul == 'true'){
	g_form.addInfoMessage("This asset is three months away from the end of its useful life. Please refrain from assigning it to an employee as a primary work device.");
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

MackI
Kilo Sage

hi @Dash2 

Whateve @Ankur Bawiskar  is true , i overlooked this matter i thought ITAM server side script.

I apologize for the oversight in my previous response. The GlideDateTime API is not directly available in client-side scripts in ServiceNow.


Here's the corrected and refined client script that uses JavaScript's native Date object instead of GlideDateTime

This script works on a scoped app with the latest Javascript native Date object but I believe it's going to work on global space as well

 

function onLoad() {
    // Ensure the 'End of Useful Life' field exists on the form
    if (g_form.hasField('cmn_end_of_useful_life')) {
        // Get the End of Useful Life date
        var eolDateString = g_form.getValue('cmn_end_of_useful_life');  // Get date as string

        // Check if EOL date is valid
        if (eolDateString) {
            // Convert string to Date object 
            var eolDate = new Date(eolDateString); 

            // Calculate the date three months from today
            var threeMonthsFromToday = new Date();
            threeMonthsFromToday.setMonth(threeMonthsFromToday.getMonth() + 3); //Add 3 months

            // Check if the EOL is within the next three months
            if (eolDate <= threeMonthsFromToday) {
                g_form.addInfoMessage("This asset is three months or less away from the end of its useful life. Please refrain from assigning it to an employee as a primary work device.");
            }
        } 
    } 
}

 

A small request from my end, If you like this opinion and your problem is resolved after reviewing and applying it. Please kindly mark this your best answer‌🌠‌ OR  mark it  Helpful ‌‌ if you think that you get some insight from this content relevant to your problem and help me to contribute more to this community

MackI | ServiceNow Technical Consultant | DXC Technology Australia | ServiceNow Practice | LinkedIn Top IT Operation Voice 2023 | Sydney,Australia