sap.ui.model.type.Date implementation based on runtime variables

<mvc:View controllerName="<PROJECT_PATH>.controller.<NAME>" xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc">
	<Page>
		<content>
			<DatePicker id="myDatePicker" value="{ path: 'viewmodel>/date', type: 'sap.ui.model.type.Date', formatOptions: { UTC: true }}"
				valueStateText="{viewmodel>/valueStateText}" minDate="{viewmodel>/dateMin}" maxDate="{viewmodel>/dateMax}"/>
		</content>
	</Page>
</mvc:View>

/*global location*/
sap.ui.define([
	"<PROJECT_PATH>/controller/BaseController",
	"sap/ui/model/json/JSONModel",
	"sap/ui/model/type/Date"
], function(
	BaseController,
	JSONModel,
	TypeDate
) {
	"use strict";

	return BaseController.extend("<PROJECT_PATH>.controller.<NAME>", {

		/**
		 * @class Controller
		 * @summary Your controller
		 */
		onInit: function() {
			this.oViewModel = new JSONModel({
				date: undefined,
				dateMin: undefined,
				dateMax: undefined,
				valueStateText: undefined
			});
			this.getView().setModel(this.oViewModel, "viewmodel");

			//do sth. then set new validation
			this._setValidationRule();
		},
		/** 
		 * @memberOf Controller
		 * @description Set sap.ui.model.type.Date based on other runtime variables
		 */
		_setValidationRule: function() {
			var oi18n = this.getResourceBundle(), //only works with BaseController.js
				oDateMin,
				oDateMax,
				sDateMin,
				oTypeDate;

			//set min and max date
			oDateMin = new Date();
			oDateMax = new Date();

			//set min and max date for the sap.m.DatePicker control
			this.oViewModel.setProperty("/dateMin", oDateMin);
			this.oViewModel.setProperty("/dateMax", oDateMax);

			//sap.ui.model.type.Date with min and max date
			oTypeDate = new TypeDate({
				UTC: true
			}, {
				minimum: oDateMin,
				maximum: oDateMax
			});

			//set personalised valueStateText
			sDateMin = oTypeDate.formatValue(oDateMin, "string");
			this.oViewModel.setProperty("/valueStateText", oi18n.getText("personalisedValueStateText", [sDateMin]));

			//bind the value to pass the new sap.ui.model.type.Date definition
			var oDatePicker = this.getView().byId("myDatePicker"); //only works with BaseController.js
			oDatePicker.bindValue({
				path: "viewmodel>/date",
				type: oTypeDate
			});

		}

	});

});

Leave a Reply

Your email address will not be published. Required fields are marked *