-->

How to input only month and year in UI5?

2020-07-24 06:13发布

问题:

Here I see I can insert a date-time input: https://ui5.sap.com/#/entity/sap.m.DateTimeInput/sample/sap.m.sample.DateTimeInput

<DateTimeInput type="Date" placeholder="Enter Date ..." />

But I want the user to choose only month and year, not the day. Is it possible?

回答1:

Yes, surprisingly easy:

Add the following attribute to your DateTimeInput: displayFormat="MM/yyyy"



回答2:

As sap.m.DateTimeInput is deprecated, sap.m.DatePicker should be used in our case.

Same as picking the year only, DatePicker now can handle displayFormat="MM/yyyy" since UI5 1.68. The picker opens then with a month picker directly.

Below is a small sample with 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="MM/yyyy"
      valueFormat="MM/yyyy"
      width="7rem"
      value="{
        path: '/myMonthYear',
        type: 'DateType',
        formatOptions: {
          pattern: 'MM/yyyy',
          source: {
            pattern: 'MM/yyyy'
          }
        },
        constraints: { maximum: '12/2030' }
      }"
    />`,
  });

  Core.getMessageManager().registerObject(control, true);
  control.setModel(new JSONModel({
    myMonthYear:  `${new Date().getMonth() + 1}/${new Date().getFullYear()}`, // current month/year, e.g. '11/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>