Client Script: On Change | multiple conditions

Spaceballs
Kilo Sage

Hi,

I created a script in the Client Script but I have multiple conditions that I need to create and it is not working.

 

 

Capture2.PNG

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        g_form.clearValue('milestone');
        return;
    }
    var addDays;
    if (g_form.getValue('priority') == "A") {
        //add days
        addDays = "56";
    }
    //get kickoff date value
    var startDate = new Date(g_form.getValue('kickoff_date'));

    var addDaysToSartDate = "";

    //get kickoff date
    var getDateFromStartDate = startDate.getDate();

    //subtract 56 days from the kickoff selected date
    var totalDays = parseInt(getDateFromStartDate) - parseInt(addDays);

    startDate.setDate(totalDays);

    //g_user_date_format representing the user's date preferred date format which is yyyy-MM-dd
    addDaysToSartDate = formatDate(startDate, g_user_date_format);

    //Retrieves a field value from the form NOT the database
    g_form.setValue('milestone', addDaysToSartDate);
}

Result

Capture.PNG

 

How can I revise the code and add multiple ifs condition

 

If Priority == A then adddays -56

else if Priority == B then adddays -6

else if Priority == C then adddays -2

else if Priority == D then adddays -10

 

Output should be in date format and should be populate in the milestone field.

 

Thanks for your help

1 ACCEPTED SOLUTION

I followed your scripts

Actually you didn't and made a couple of fundamental mistakes because of which the GlideAjax handler Script Include will not work 😀:

- you added an initialize method to the Script Include - should not be done (it can ba done, but that's a topic for another day) and the Script Include provided does not contain one:

var communityDates = Class.create();
communityDates.prototype = {
	// this method must not exist
	initialize: function () {},
	...

- the class does not extend AbstractAjaxProcessor; proposed code:

var communityDates = Class.create();
communityDates.prototype = Object.extendsObject(AbstractAjaxProcessor, {
...

your code:

var communityDates = Class.create();
communityDates.prototype = {
...

But given that your are working in scope, the proposed code is also not OK; it should be:

var communityDates = Class.create();
communityDates.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
...

notice the extra global. scope name in front of AbstractAjaxProcessor.

Now this is not an error, but in the Client Script one can forego

var answer = trigger.responseXML.documentElement.getAttribute('answer');

in

function getDatedata (trigger) {
	var answer = trigger.responseXML.documentElement.getAttribute('answer');
	...

if, when calling the GlideAjax handler, instead of

gar.getXML(getDatedata);

one writes

gar.getXMLAnswer(getDatedata);​

in that case the parameter of function getDatedata alreade is "answer":

function getDatedata (answer) {
	...

Than another big problem is trying to crate a GlideDateTime directly from the date value arriving from the client side through parameters. GlideDateTime can only correctly decode format YYYY-MM-DD HH:mm:ss - which is the internal Date/time format. It also expects that value to be in UTC TZ, which for +95% of user on the planet will not be the case. In other cases the system will try to guess the format used, but half the time a date where the day is 12 or less than that - e.g. 3/2/2023 - will not be correctly decoded.

The solution to correctly getting the value of a Date or Date/time field client side is to use a function provided by ServiceNow (getDateFromFormat) and one of two variables also provided by ServiceNow (g_user_date_format and g_user_date_time_format). In your case:

var kickoffDateValue = getDateFromFormat(g_form.getValue('kickoff_date'), g_user_date_format);

This will place the date value as a Unix epoch millisecond into variable kickoffDateValue. This can be used both to correctly initialize a Date object client side or a GlideDate or a GlideDateTime server side.

 

So in the onChange client script you could write:

var kickoffDateValue = new Date(getDateFromFormat(g_form.getValue('kickoff_date'), g_user_date_format));

Thus you don't need a GlideAjax call or Script Include; the client side code could be something like:

function onChange (control, oldValue, newValue, isLoading, isTemplate) {
	if (isLoading || newValue === '') {
		return;
	}

	var priorityOffsetDB = {
		'A': -56,
		'B': -6,
		'C': -2,
		'D': -10,
	};

	var kickoffDate = new Date(getDateFromFormat(g_form.getValue('kickoff_date'), g_user_date_format));
	var priority = g_form.getValue('priority');

	if (typeof priorityOffsetDB[priority] != 'undefined') {
		kickoffDate.setDate(kickoffDate.getDate() + priorityOffsetDB[priority]);
		g_form.setValue('milestone', formatDate(kickoffDate, g_user_date_time_format));
	}
}

 

View solution in original post

20 REPLIES 20

Matt102
Giga Guru

Hi,

I'd maybe start with something like the following.
You could start out getting the basics right, by explicitly setting the return of the calcDate function, then develop the function...

 

var priority = g_form.getValue('priority');
var startDate = g_form.getValue('kickoff_date');
var diff;

switch (priority) {
    case 'A':
        diff = 56;
        break;
    case 'B':
        diff = 6;
        break;
    case 'C':
        diff = 2;
        break;
    case 'D':
        diff = 10;
        break;
}

calcDate(d,i) {
    /*
        do your date diff calc and
        formatting inside here
    */
   return YYYY-MM-DD
}

g_form.setValue('milestone', calcDate(startDate, diff));

Hi @Matt102 ,

 

Thank you for your help but I'm not too familiar with Java language and what syntax is missing causing the error?

What expression of datediff do I need to insert? 

 

Spaceballs_0-1673448873462.png

Hi,

Yeh I understand, it's not good with not being familiar with something plus it being a tricky area.

All I could do is stand on the shoulders of Giants, *Chucky T* in "Adding days to date field in client script " suggests another post as having best solutions, I suspect it was on an old forum, but believe it is likkely to be this post: Client Script Date/Time Functions  
Number 9. addDateAmount should give you what you want, as far as you client script code goes.
As far as I understand it you would implement server side the Script Include (ClientDateTimeUtils Script Include - in similar fashion/logic to what Bharath62 SUGGESTS) then use the javascript provided in #9, in your client scipt, to Ajax call the Script Include.

HTH,Matt

NB/FWIW working with this type of stuff is always better with a bit of knowledge (which I understand you may not have time now to acquire) - SN OnDemand training recomend the CodeAcademy JavaScript course as a primer...

 

BharathChintala
Mega Sage

You have to use GlideAjax for this as GlideDate obeject won't work in Client also you can't do addition of dates in noraml way. Please use below script

 

Client script:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var cin = g_form.getValue('approved_start_date');
var prio = g_form.getValue('priority');
alert(cin);
alert(prio);
var gar = new GlideAjax('communityDates');
gar.addParam('sysparm_name', 'getDate');
gar.addParam('sysparm_value_cin', cin);
gar.addParam('sysparm_value_prio', prio);
gar.getXML(getDatedata);
}

function getDatedata(trigger) {
var answer = trigger.responseXML.documentElement.getAttribute('answer');
alert(answer);
g_form.setValue('approved_start_date', answer);

}

Bharath62_1-1673450879212.png

 

Script include:

var communityDates = Class.create();
communityDates.prototype = Object.extendsObject(AbstractAjaxProcessor,{
getDate: function() {
var cin = new GlideDateTime(this.getParameter('sysparm_value_cin'));
var prio = this.getParameter('sysparm_value_prio');
if (prio == 1) { // this will be A
cin.addDays(-56);
} else if (prio == 2) { // this will be B
cin.addDays(-6);
} else if (prio == 3) { // this will be C
cin.addDays(-2);
} else if (prio == 4) { // this will be D
cin.addDays(-10);
}
return cin.getDate();
},
type: 'communityDates'
});

Bharath62_0-1673450849618.png

Thanks,

Bharath

If my inputs have helped with your question, please mark my answer as accepted solution, and give a thumb up.
Bharath Chintala

Hi @BharathChintala ,

Thank you for your suggestion, I followed your scripts but the milestone date field is not populating any value. Any idea?

Client Script

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        //g_form.clearValue('milestone');
        return;
    }
    var cin = g_form.getValue('kickoff_date');
    var prio = g_form.getValue('priority');
    //alert(cin);
    //alert(prio);
    var gar = new GlideAjax('communityDates');
    gar.addParam('sysparm_name', 'getDate');
    gar.addParam('sysparm_value_cin', cin);
    gar.addParam('sysparm_value_prio', prio);
    gar.getXML(getDatedata);
}

function getDatedata(trigger) {
    var answer = trigger.responseXML.documentElement.getAttribute('answer');
    //alert(answer);
    g_form.setValue('kickoff_date', answer);
}

 

 

Script Include

 

var communityDates = Class.create();
communityDates.prototype = {
    initialize: function() {},
    getDate: function() {
        var cin = new GlideDateTime(this.getParameter('sysparm_value_cin'));
        var prio = this.getParameter('sysparm_value_prio');
		
        if (prio == 'a') { // this will be A
            cin.addDays(-56);
			
        } else if (prio == 'b') { // this will be B
            cin.addDays(-6);
        }
		
        return cin.getDate();
    },
    type: 'communityDates'
};

 

Output

Spaceballs_0-1673457318689.png