sap.m.Select: start with a blank selection input element

19,118

Solution 1

Currently, no. There seems to be no better way. There is a ticket for that on GitHub.

Solution 2

Since the OpenUI5 version 1.34, you can set the forceSelection property to false.

The forceSelection property indicates whether the selection is restricted to one of the items in the list. The default value is true (which means, if the selection is not set, the first item in the dropdown list is selected).

When to set it to false?

If you do not want a default item to be pre selected.

Additional information https://github.com/SAP/openui5/commit/b2191fd50e2115f8f9d2db7604a75fb50c57591f

Solution 3

It's also my opinion to avoid messing with the dataset and much liked the idea of adding an additional item aggregate. However my improvement on this is to use a formatter on the control itself so it is clearly visible and executed at the right time. I make use of a formatter with fully qualified controller to get the control as 'this' parameter. In the formatter function I add a ListItem, as proposed by @Victor S

In XML view

<Select forceSelection="false" selectedKey="{model>/key}" items="{path: 'model>/Items'}" icon="{path: '', formatter: 'mynamespace.Utils.addDeselectOption'}">

In the Utils controller:

addDeselectOption: function() {
    var that = this;
    this.getBinding("items").attachDataReceived(function(){
        that.insertItem(new sap.ui.core.ListItem({text: '', key: undefined}), 0);
    });
}

Works form me in UI5 1.52

Solution 4

Even though this solution is not great, I managed to get the empty field stick by adding both, the forceSelection=false property, and also in the controller's onInit function (I used the Select element):

    var codeField = this.getView().byId("codeField");
    setTimeout(function() {
        codeField.insertItem(new sap.ui.core.ListItem({text: '', key: undefined}), 0);
    }, 1000);

If the forceSelection=false is left out, the field will load either too early or too late to the drop down, which will cause the wrong selection to be visible. Hope it helps someone.

Share:
19,118
Jorg
Author by

Jorg

SAP by day, JS by night. These days they overlap a lot #UI5

Updated on June 14, 2022

Comments

  • Jorg
    Jorg almost 2 years

    When using a data aggregation on sap.m.Select, the first entry is always selected. Here's a link to the SDK's preview.

    Example code from my app

    new sap.m.Select("id-names", {
        width: '100%',
    }).bindAggregation("items", "data>/trip/names", new sap.ui.core.Item({
        text: "{data>Name}"
    }));
    

    There is a parameter called selectedKey on the constructor to change this to another index. What I want is the select to be blank, because I want to force my users to make a choice, not blandly accept the first entry in the list.

    I could force an blank entry in my aggregation data>/trip/names but that would pollute my list.

    Is there a better way to achieve this?