restricting a date field

patricklatella
Mega Sage

Hi helpful friends!

reposting this...I've gotten help already (thanks guys!) with several codes that I could not get to work properly and have gotten my head pretty spun around jumbling 3 different solutions, which again unfortunately I could not get to work.   Looking to start fresh.   Seeing lots of entries in the community on this but with the wide degree of differences in restrictions people are shooting for I'm having difficulty extrapolating.

I have a date field on a catalog item that I need to put restraints on.

I need it to only allow an entry of a date 6 or more BUSINESS days in the future.

the name of my date field is "needed_by"

Any help is most appreciated!

1 ACCEPTED SOLUTION

amlanpal
Kilo Sage

Hi Patrick,



You need to write the onChange Catalog Client Script on change of the variable named 'needed_by' and call a Script include where the validations are done. Please find the scripts for that here. Please refer my response on this thread: Issue related to Date/Time variable



Client Script:



function onChange(control, oldValue, newValue, isLoading, isTemplate) {


      if (isLoading || newValue === '') {


              return;


      }



      var cdt = newValue; //The date field



      var dttype = 'day'; //this can be day, hour, minute, second. By default it will return seconds.



      /******** This Checks whether the selected date is in the Past or Not************************/



      var ajax = new GlideAjax('ClientDateTimeUtils_New');


      ajax.addParam('sysparm_name','getNowDateTimeDiff');


      ajax.addParam('sysparm_fdt', cdt);


      ajax.addParam('sysparm_difftype', dttype);


      ajax.getXML(doSomething);



      function doSomething(response){


              var answer = response.responseXML.documentElement.getAttribute("answer");


              if(answer<0){


                      alert("Date & Time should not be Prior to Current Date & Time");


                      g_form.clearValue('date'); // Pass the variable name here


                      g_form.setMandatory('date', true);



              }


      }



 


      /************* This Checks whether the selected date is within 6 business day ahead & Not weekend**********/



   


      var ga = new GlideAjax('ClientDateTimeUtils_New');


  ga.addParam ('sysparm_name','isBusinessDay');


  ga.addParam ('sysparm_schedule_name','8-5 weekdays');


  ga.addParam ('sysparm_dateTime',newValue);


  ga.getXML(CheckScheduleAgainstDatesParse);



  function CheckScheduleAgainstDatesParse (response) {


  var answer = response.responseXML.documentElement.getAttribute("answer");


  if(parseInt(answer)>63){ //For 6 days with 9 hour per day


                      alert("Date should be within 6 business days & within business working hours");


                      g_form.clearValue('date');


                      g_form.setMandatory('date', true);



              }


 


  }


}



Script Include:


var ClientDateTimeUtils_New = Class.create();


ClientDateTimeUtils_New.prototype = Object.extendsObject(AbstractAjaxProcessor, {


  //Takes a Single Date/Time Field and returns its time difference from nowDateTime().


  //params = sysparm_fdt (the first date/time field), sysparm_difftype (time based format to return result. See "_calcDateDiff" function comments)



  getNowDateTimeDiff: function(){


  var diff;


  var firstDT = this.getParameter('sysparm_fdt'); //First Date-Time Field


  var diffTYPE = this.getParameter('sysparm_difftype'); // Date-Time Type to return the answer as. Can be second, minute, hour, day



  diff = gs.dateDiff(gs.nowDateTime(), firstDT, true);


  var timediff = this._calcDateDiff(diffTYPE, diff);


  return timediff;


  },





  //Private function to calculate the date difference return result in second, minute, hour, day.


  _calcDateDiff: function(diffTYPE, seconds){


  var thisdiff;


  if (diffTYPE == "day"){thisdiff = seconds/86400;}


  else if (diffTYPE == "hour"){thisdiff = seconds/3600;}


  else if (diffTYPE == "minute"){thisdiff = seconds/60;}


  else if (diffTYPE == "second"){thisdiff = seconds;}


  else {thisdiff = seconds;}


  return thisdiff;


  },



  //Takes a GlideDate field and schedule


  //Returns true if the date falls within the given schedule and within today+6 Business days, false otherwise.


  isBusinessDay: function (){


  var sched;


  var rslt;


  var dur = 64;


  var schedname = this.getParameter('sysparm_schedule_name');


  var date_time = this.getParameter('sysparm_dateTime');



  var schedRec = new GlideRecord('cmn_schedule');


  schedRec.get('name', schedname);



  //automatically use correct API for instance build


  if (typeof GlideSchedule != 'undefined')


  sched = new GlideSchedule(schedRec.sys_id);


  else


  sched = new Packages.com.glide.schedules.Schedule(schedRec.sys_id);



  //Get the date/time in correct format


  var DateTime = new GlideDateTime();


  DateTime.setDisplayValue(date_time);


  rslt = sched.isInSchedule(DateTime);



  if (rslt){


  var myUserTZ = gs.getUser().getTZ();


  var dc = new DurationCalculator();


  dc.setSchedule(schedRec.sys_id);


  dc.setTimeZone(myUserTZ);


  dur = dc.calcScheduleDuration(gs.now(), date_time)/3600;


  }


  return dur.toString();


  }



});



I hope this helps.Please mark correct/helpful based on impact


View solution in original post

20 REPLIES 20

patricklatella
Mega Sage

find_real_file.png



screen shot, no error


patricklatella
Mega Sage

Hi Amlan,


I believe I'm getting it work, had the name of the script include wrong and just need to make a couple tweaks...thanks!


patricklatella
Mega Sage

Hi Amlan,


still struggling to get this to work properly.   One thing is that because I need it to only allow dates at least 6 business day AFTER today, then I believe this part:



if(parseInt(answer)>63){ //For 6 days with 9 hour per day



is backwards.   However when I change it to "<63", then it does nothing.



Also, does it matter if my "needed_by" date field is a "date" type variable?   and not a "date/time" variable?



patricklatella
Mega Sage

thanks everyone for your help, this was achieved with the following client script and script include:



client script:




function onChange(control, oldValue, newValue, isLoading, isTemplate) {




  g_form.hideFieldMsg('needed_by');



      if (isLoading || newValue === '') {




              return;




      }




/************* This Checks whether the selected date is within 5 business day ahead**********/




  var ga = new GlideAjax('ourcompanyClientDateTimeUtils');


  ga.addParam ('sysparm_name','withinBusinessHours');


  ga.addParam ('sysparm_hours','36');


  ga.addParam ('sysparm_requestedDate',newValue);


  ga.getXML(CheckScheduleAgainstDatesParse);


}



  function CheckScheduleAgainstDatesParse (response) {




  var answer = response.responseXML.documentElement.getAttribute("answer");


  if(answer == 'False'){




                      g_form.showFieldMsg('needed_by','Please allow at least 5 business days','error');


                      g_form.clearValue('needed_by');


              }



and the script include was:



var ourcompanyClientDateTimeUtils = Class.create();


ourcompanyClientDateTimeUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {




  withinBusinessHours: function() {




  var retVal; // Return value


  var pn     = this.getParameter('sysparm_hours');


  var requestedDate= this.getParameter('sysparm_requestedDate');


  var reqDateTime = new GlideDateTime(requestedDate);



  gs.log(reqDateTime);



  if(pn > 0){


      //Get a schedule by sys_id to calculate duration


  var schedule = new GlideSchedule();


  schedule.load('090eecae0a0a0b260077e1dfa71da828');




      //Get the current date/time in correct format for duration calculation


      var actualDateTime = new GlideDateTime();


      actualDateTime.setDisplayValue(gs.nowDateTime());


  //Create variable to capture the date we want to compare against


  //requestedDate = new GlideDateTime("2017-06-16 00:00:00");


  //Date difference calculated based on specified schedule


  var difDay = schedule.duration(actualDateTime,reqDateTime).getDayPart()*24;


  var difHour = schedule.duration(actualDateTime,reqDateTime).getDurationValue().split(':')[0].substr(-2);




  var dif = difDay + parseInt(difHour.replace(/^[0]+/g,""));




  if(dif >= pn){


  retVal = "True";


  } else {


  retVal = "False";


  }


  gs.log(retVal);


  return retVal;


  }



  },




  type: "ourcompanyClientDateTimeUtils"


});


Hoping you're still on to get this message - your answer was EXACTLY what I needed.

Thank you from the bottom of my hear. Saved me and my company money and hours here. 🙂 Cheers!