livesearch

Live Search functionality in sapui5 list control

Pre-requisites

1.sapui5 framework
2.basic javascript knowledge

What we are going to do is simple.We have a List with data.We also have a Search field.When we search the data in the list is refined based on the searchfield you entered live.We are using liveChange event of sap.m.SearchField control to achieve this.



Steps

1.Create a list and bind data to the list.

var oModel = new sap.ui.model.json.JSONModel({
    "Data": [{
        "firstname": "ricky",
        "lastname": "martin"
    }, {
        "firstname": "philip",
        "lastname": "morrs"
    }, {
        "firstname": "arnold",
        "lastname": "schwarzenegger"
    }]
});
sap.ui.getCore().setModel(oModel, "myModel");


oList = new sap.m.List("oList", {});
oListItem = new sap.m.StandardListItem({
    title: "{firstname} {lastname}"
});
oList.setModel(sap.ui.getCore().getModel("myModel"));
oList.bindAggregation("items", "/Data", oListItem);

2.Create search field control.
 searchL = new sap.m.SearchField({});
3.Get the search field value.
 var like = evt.getSource().getValue();


4.Implement search in liveChange event.
 liveChange:function(evt) {
    var like = evt.getSource().getValue();
    var binding = sap.ui.getCore().getControl("oList").getBinding("items");

    var filters = [
        new sap.ui.model.Filter("lastname", sap.ui.model.FilterOperator.Contains, like),
        new sap.ui.model.Filter("firstname", sap.ui.model.FilterOperator.Contains, like)

        // Add additional filters  
    ];
    var oFilter = new sap.ui.model.Filter({
        aFilters: filters,
        bAnd: false,
        _bMultiFilter: true
    }); // true = AND, false = OR  

    binding.filter(oFilter);
},
tooltip: "Search for objects..",
});

If we set bAnd to true both filters are AND ed.Here we are using OR functionality ie either firstname or lastname contain search value it will show up.

Iam sharing sample code
If you enjoyed this post, Please Share!!

0 comments :

Post a Comment

Powered by Blogger.