Search code examples
javascriptdrop-down-menusapui5sap-fiori

Select an item from a selectbox according to a specific column


I'd like to select a specific line according to a column (Xfeld, SAP expert will understand).

Here is my code and a sample of data :

 <Select id="areaSelect" items="{path: '/AreaSet'}" selectedKey="{=${/AreaSet}.find(function(o){return o.Xfeld === 'X';}).ZArea}">
     <core:Item key="{ZArea}" text="{Name}" />
    </Select>

Sample data :

"Zarea" "Name" "Xfeld"
"Area1" "Area1desc" "X"
"Area2" "Cat2desc" " "

Solution

  • Javascript code in the XML syntax beyond the specifications defined for binding will not work. You can set a selected item by using a formatter in your code. The formatter function will set a selected key when the item is created and the flag in your column is set.

    <Select id="areaSelect" items="{path: '/AreaSet'}" >
            <core:Item key="{
                parts : [
                    {path: 'ZArea'},
                    {path: 'Xfeld'}
                ],
                formatter: '.formatter.setSelection'
            }" 
            text="{Name}" />
    </Select>
    

    In your controller add the formatter

    ...
    ...
        "com/sap/app/controller/BaseController",
        "sap/ui/model/json/JSONModel",
        "com/sap/app/model/formatter"
    ], function (BaseController, JSONModel, formatter) {
    
       BaseController.extend("com.sap.app.controller.Detail", {
           formatter: formatter,
           onInit: function () {
    ...
    ...
    

    In your fomatter define a function which will set the selected item key.

    sap.ui.define([], function () {
    "use strict";
    return {
        setSelection : function(key, isSelected){
            if(isSelected=="X"){
                var oSelect = this.byId("areaSelect");
                oSelect.setSelectedKey(key);
            }
            return key;
        }
    }
    });