How to set Umbraco CMS DateTime Picker programmatically in angularJs

In this short article, I am going to show the steps needed to set up date-time control programmatically in Umbraco CMS back office.

Recently, I had to refresh the date time picker control value under certain business-logic conditions directly in the angularJs controller.

I had some issues, so I decided to write this text and share my working code.

My working project was based on Umbraco 8.4.0.

Before we start, it is worth mentioning that <umb-date-time-picker> directive uses flatpickr - a lightweight and powerful date time picker. 

I encourage you to read the official documentation on https://flatpickr.js.org/ website and check this thread https://github.com/flatpickr/flatpickr/issues/484.

It took me a while to find this, so hopefully, you can save some time ⌛.

We can certainly find a lot more interesting things to do than messing around with the good old 👴 angularJs 🙂.

Let's go!

View, Controller setup

Let's assume the following setup:

The view

In my case, <umb-date-time-picker> directive in html view looked as follows:

<umb-date-time-picker ng-model="vm.dateFrom"
            options="vm.dateTimeConfig"
            on-change="vm.datePickerFromChange(selectedDates, dateStr, instance)">
</umb-date-time-picker>

Datetime picker config settings 

$scope.vm.dateTimeConfig = {
        enableTime: true,
        dateFormat: "d/m/Y H:i",
        time_24hr: true
 };

Initial dateFrom setup:

$scope.vm.dateFrom = "12/03/2020 15:45";

Handy function converting datetime string to Date() object:

function convertToDateTime(sDateTime) {
	sDateTime = sDateTime.split(" ");

	var date = sDateTime[0].split("/");
	var yyyy = date[2];
	var mm = date[1] - 1;
	var dd = date[0];

	var time = sDateTime[1].split(":");
	var h = time[0];
	var m = time[1];

	return new Date(yyyy, mm, dd, h, m, 0);
}

Setting Umbraco DateTime Picker value in angularJs

First, you need to retrieve the current flatpickr instance.

Then just use setDate() function https://flatpickr.js.org/instance-methods-properties-elements/#setdate-date-triggerchange-datestrformat .

According to the documentation:

Before setting the value I had to convert the string value to a Date object using convertToDateTime function.

For some reason, setting the string value directly did not work for me.

The whole working snippet looked as follows:

let currentFlatpickrInstance = document.getElementsByClassName("flatpickr-input")[0]._flatpickr;
currentFlatpickrInstance.setDate(convertDateTime("12/08/2030 15:45"))

Final words

I hope you find this short post useful and you can adapt it to your needs. 

That's it, have a nice day! 👌

Comments
Leave a Comment