Passing and getting Date object to and from date and datetime fields

Another new feature we introduced in FormsDesigner 3.0.1 is the ability to interact with date and datetime fields by passing JavaScript Date objects. This feature takes away the need for consumer to think about parsing dates in locale specific formats and simplifies the way date operations are performed on date/datetime fields. Let us take a look at the following use case.

Here we have our old form for creating new issues. Suppose the priority of an issue we set affects the due date for its resolution: high priority implies that the issue is to be resolved within two days, normal priority implies a 5 day period and low priority leaves the due date undefined.

Because the due date periods are pre-defined and are standard for all issues, we want to auto-assign them based on the priority we set. Here’s how we’ll go about doing it: get the current Date object, add the required number of days to it and set the object to our Due Date field.

This is the code we added to our form to achieve this effect:

function setDate(){
  var date = new Date();

  switch (fd.field('Priority').value()) {
    case 'High':
      date.setDate(date.getDate() + 2);
      break;
    case 'Normal':
      date.setDate(date.getDate() + 5);
      break;
    default:
      date = null;
  }

  fd.field('DueDate').value(date);
}

setDate();

fd.field('Priority').change(setDate);

What this code does is:

  1. It defines setDate() method which:
    • Creates a Date object which is initialized with the current date.
    • Checks the value inside the Priority field and depending on it, gets the current date value and adds the respective days offset value.
    • Sets the resulting date object to the field.
  2. It calls the setDate() method when the form is loaded.
  3. And it defines a change event, which calls the setDate() method whenever the Priority value changes.

Now, after we’ve saved our form, we can open it up and see how it works.

Whenever we change the priority value, the due date is automatically readjusted:

High priority.

Normal priority.

Low priority.

Note

This approach is particularly advantageous if your form is potentially browsed in environments with varying locales, as different locales mean different date formats, which our JavaScript functions take care of.

Recommend this: