1

I am trying to achieve the following in JavaScript for CRM 2013

If a date field

gteq_expirydate

is within the next 45 days set an alert onchange.

How do I do it?

Rahul Purush
  • 125
  • 1
  • 9
  • 1
    Are you stuck in a part of your javascript? If so please post some of your code, or explain what has you stumped. If you need some links on Javascript and CRM: https://msdn.microsoft.com/en-us/library/hh771584(v=crm.6).aspx & Joe CRM has some useful info here https://www.powerobjects.com/blog/2011/01/14/crm-2011-useful-javascript-tidbits/ – Bactos Jan 25 '15 at 22:51

2 Answers2

1

Add days to JavaScript Date use this example to do operation on javascript dates, then run a simple comparison.

var crmDate = Xrm.Page.getAttribute("gteq_passportexpirydate").getValue();
var today = new Date();
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+45);
if(crmDate < tomorrow && crmDate >= today){
    alert("care");
}

If you need to compare the old value of the date field with the new value that you write in the date field, you will need another field called "old date field" to run the comparison, otherwise the value you will retrieve will be the new one.

Community
  • 1
  • 1
Mauro De Biasio
  • 1,146
  • 6
  • 16
  • Ok thanks for this, this is where I have got to but I have a feeling a maybe going slightly off track. function PassportExpiry() { if (Xrm.Page.getAttribute("gteq_passportexpirydate").getValue() != null) { var today = new Date(); var tomorrow = new Date(today); tomorrow.setDate(today.getDate()+45); if(date field < tomorrow && date field >= today){ alert("Passport Expires Within 45 Days"); } } } – Jon Bathurst Jan 27 '15 at 06:21
  • Hi I modified the scripr you sent me check the conditions now :) – Mauro De Biasio Jan 27 '15 at 10:33
  • Ok that has worked perfect. thanks for that, really appreciate your time. – Jon Bathurst Jan 27 '15 at 11:37
1

Take a look at Moment JS to assist with this requirement (no connection to the project, just have found it very helpful in CRM for these types of requirements.)

You need to to add the moment.js library and an OnChange event for the field similar to this:

function checkDateOnChange (e) {
 var dateField = e.getEventSource();

 var newDate = e.getValue();

 if (moment.isDate(newDate) && moment(newDate).isBefore(moment().Add(45, 'days')))
    alert("Date is 45 or less days in the future.");
}

Besides simplicity of implementation it makes the code very readable when you look at it in the future because of the fluent style.

Nicknow
  • 7,154
  • 3
  • 22
  • 38