Search code examples
inputodatasapui5search-suggestion

SAPUI5 sap.m.Input - Suggestion values


How do I enable live suggestions with reading from my odata Service for a single cell in my table?

oTable.addColumn(new sap.ui.table.Column({
                template : new sap.m.Input({
                    value : column, // also works, its dynamic
                    textAlign : sap.ui.core.TextAlign.Center,
                    inputType : Text,
                    type : sap.m.InputType.Text,
                    showSuggestion : true,
                    liveChange : function() {
                        if (this.getValue().length > 0) {
                            var oModel = new sap.ui.model.json.JSONModel();
                            var value = this.getValue();
                            var serviceUrl = "/sap/opu/odata/SAP/XXXX_SRV/SuggestionsSet/?$filter=startswith(Key,'" + value + "')";
                            oModel.loadData(serviceUrl, null, false, "GET", false, false, null);

                            this.destroySuggestionItems();
                            for (var i = 0; i < oModel.oData.d.results.length; i++) {
                                this.addSuggestionItem(new sap.ui.core.Item({
                                    text: oModel.oData.d.results[i].Key,
                                }));
                            } // everything seems fine, but no Suggestion opens..


                        }
                    },
                }),
                visible : true,
            }));

Solution

  • See the explored example. However, in your case the model is an ODataModel, but that does not really matter... As you can see in the examples's code you can also use

    showSuggestion="true"
    suggest="handleSuggest"
    suggestionItems="{/ProductCollection}"
    

    In the handler you then do this (copied from the example as well):

    handleSuggest: function(oEvent) {
        var sTerm = oEvent.getParameter("suggestValue");
        var aFilters = [];
        if (sTerm) {
            aFilters.push(new Filter("Name", sap.ui.model.FilterOperator.StartsWith, sTerm));
        }
        oEvent.getSource().getBinding("suggestionItems").filter(aFilters);
    }
    

    Basically you - create one or more filters - get the binding for the suggestionItems aggregation - call .filter(...) on the binding and pass the filter(s)

    There is no need to code that stuff manually (i.e. GET request etc.).

    Here is a runninh example for you (run via jsbin), see below. In your case all you do is bind to

    suggestionItems="{path:'/SuggestionSet', templateShareable:false}">
    

    In the handleSuggest handler you would then get the the value for the Key property of the SuggestionSet that belongs to current/corresponding input field in order to instantiate a new Filter. You could get the Key from the BindingContext I guess...

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8" />
            <title>SAPUI5 single file template | nabisoft</title>
            <script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
                id="sap-ui-bootstrap"
                data-sap-ui-theme="sap_bluecrystal"
                data-sap-ui-libs="sap.m"
                data-sap-ui-bindingSyntax="complex"
                data-sap-ui-compatVersion="edge"
                data-sap-ui-preload="async"></script>
                <!-- use "sync" or change the code below if you have issues -->
    
                <!-- XMLView -->
                <script id="myXmlView" type="ui5/xmlview">
                    <mvc:View
                        controllerName="MyController"
                        xmlns="sap.m"
                        xmlns:core="sap.ui.core"
                        xmlns:mvc="sap.ui.core.mvc">
    
                        <Table
                            id="myTable"
                            growing="true"
                            growingThreshold="10"
                            growingScrollToLoad="true"
                            busyIndicatorDelay="0">
                            <columns>
                                <Column>
                                    <Text text="Customer ID"/>
                                </Column>
                                <Column>
                                    <Text text="Company Name"/>
                                </Column>
                            </columns>
                            <items>
                                <!-- filled via bindItems() in controller -->
                            </items>
                        </Table>
    
                    </mvc:View>
                </script>
    
                <!-- XML Fragment -->
                <script id="myXMLFragment" type="ui5/fragment">
                    <core:FragmentDefinition
                        xmlns="sap.m"
                        xmlns:core="sap.ui.core">
                        <ColumnListItem type="Active">
                            <cells>
                                <ObjectIdentifier title="{CustomerID}"/>
    
                                <Input
                                    value="{CompanyName}"
                                    showSuggestion="true"
                                    suggest="handleSuggest"
                                    suggestionItems="{path:'/Customers', templateShareable:false}">
                                    <suggestionItems>
                                        <core:Item text="{CompanyName}" />
                                    </suggestionItems>
                                </Input>
    
                            </cells>
                        </ColumnListItem>
                    </core:FragmentDefinition>
                </script>
    
    
            <script>
                sap.ui.getCore().attachInit(function () {
                    "use strict";
    
                    //### Controller ###
                    sap.ui.controller("MyController", {
                        onInit : function () {
    
                            this.getView().setModel(
                                new sap.ui.model.odata.v2.ODataModel("https://cors-anywhere.herokuapp.com/services.odata.org/V2/Northwind/Northwind.svc/", {
                                    json : true,
                                    useBatch : false
                                })
                            );
    
                            var sPath = "/Customers";
                            var oTable = this.byId("myTable");
                            var oTemplate =  sap.ui.xmlfragment({
                                fragmentContent : jQuery("#myXMLFragment").html()
                            });
    
                            oTable.bindItems(sPath, oTemplate, null /*oSorter*/, null /*aFilters*/);
                        },
                        handleSuggest: function(oEvent) {
                            var sTerm = oEvent.getParameter("suggestValue");
                            var aFilters = [];
                            if (sTerm) {
                                aFilters.push(new Filter("CompanyName", sap.ui.model.FilterOperator.StartsWith, sTerm));
                            }
                            oEvent.getSource().getBinding("suggestionItems").filter(aFilters);
                        }
                    });
    
                    //### THE APP: place the XMLView somewhere into DOM ###
                    sap.ui.xmlview({
                        viewContent : jQuery("#myXmlView").html()
                    }).placeAt("content");
    
                });
            </script>
    
        </head>
    
        <body class="sapUiBody">
            <div id="content"></div>
        </body>
    </html>