padibro
padibro

Reputation: 1382

Use sap.m.DatePicker to select only year

I have a date. It is a string in the JSONModel (for example '2016'), shown by DateTimeInput:

<DateTimeInput
  value="{year}"
  displayFormat="yyyy"
  valueFormat="yy"
/>

sapui5 screenshot of datetimeinput year only

However, DateTimeInput is deprecated and I want replace it by DatePicker:

<DatePicker
  value="{year}"
  displayFormat="yyyy"
  valueFormat="yy"
/>

But when the click on the value help, the picker shows the calendar, not the list of years only.

Upvotes: 1

Views: 7708

Answers (1)

Boghyon Hoffmann
Boghyon Hoffmann

Reputation: 18044

As of UI5 1.68, DatePicker is capable of displaying the year-picker only. To enable it, displayFormat and valueFormat should be "yyyy".

Below is a small demo, including binding and validation:

sap.ui.getCore().attachInit(() => sap.ui.require([
  "sap/ui/core/Fragment",
  "sap/ui/model/json/JSONModel",
  "sap/ui/core/Core",
], async (Fragment, JSONModel, Core) => {
  "use strict";

  const control = await Fragment.load({
    definition: `<DatePicker xmlns="sap.m" xmlns:core="sap.ui.core"
      core:require="{ DateType: 'sap/ui/model/type/Date' }"
      maxDate="{/maxDate}"
      class="sapUiTinyMargin"
      displayFormat="yyyy"
      valueFormat="yyyy"
      width="7rem"
      value="{
        path: '/myYear',
        type: 'DateType',
        formatOptions: {
          pattern: 'yyyy',
          source: {
            pattern: 'yyyy'
          }
        },
        constraints: { maximum: 2030 }
      }"
    />`,
  });

  Core.getMessageManager().registerObject(control, true);
  control.setModel(new JSONModel({
    myYear: new Date().getFullYear(), // current year, e.g. 2019
    maxDate: new Date("2030-12-31") // control awaits a JS date object for maxDate
  })).placeAt("content");
}));
<script id="sap-ui-bootstrap"
  src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core, sap.m, sap.ui.unified"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-async="true"
  data-sap-ui-compatversion="edge"
  data-sap-ui-xx-waitfortheme="init"
></script><body id="content" class="sapUiBody"></body>

sapui5 datepicker year only

enter image description here

Upvotes: 3

Related Questions