add second filter without removing the existing ones - sapui5

Hi i have a searchfield with this code behind it:
onSearch : function (oEvent) {
if (oEvent.getParameters().refreshButtonPressed) {
// Search field's 'refresh' button has been pressed.
// This is visible if you select any master list item.
// In this case no new search is triggered, we only
// refresh the list binding.
this.onRefresh();
} else {
var andFilter = [];
var sQuery = oEvent.getParameter("query");
if (sQuery && sQuery.length > 0) {
// add filters
var oTableSearchState = [];
oTableSearchState = [new Filter("Supplier", FilterOperator.Contains, sQuery), new Filter("BusArea", FilterOperator.Contains, sQuery), new Filter("CostCenter", FilterOperator.Contains, sQuery),
new Filter("FuncArea", FilterOperator.Contains, sQuery)];
andFilter.push(new Filter(oTableSearchState, false));
}
this._applySearch(andFilter);
}
},
And a filter button that should add aditional filters. Something like this:
onSetFilter : function(oEvent) {
var andFilter = [];
andFilter.push(new Filter("BusArea", FilterOperator.EQ, "5000"));
this._applySearch(andFilter);
},
But of course the "BusArea" part should be dependent on what filters are selected. It could be more than 1 filter. the _applySearch function looks like this:
_applySearch: function(andFilter) {
var oViewModel = this.getModel("worklistView");
this._oTable.getBinding("items").filter(andFilter, true);
// changes the noDataText of the list in case there are no filter results
if (andFilter.length !== 0) {
oViewModel.setProperty("/tableNoDataText",
this.getResourceBundle().getText("worklistNoDataWithSearchText"));
}
}
the problem is that when i add a filter via the filter button, the filters from the searchbar disappear and the other way arround. how can i change my code so that i can add the filters without removing the existing ones?

One solution is to get the Filters from the binding info and push back together with the new Filter using and.
this._oTable.getBindingInfo("items").filters.aFilters;

After our conversation on the chat, I have made this snippet using a global model.
https://jsbin.com/pewavuhonu/edit?html,output
The ComboBox and the Button simulates your Dialog.
The input simulates the SearchField
Both are binded against the global "filtersModel", and both call the _calculateFilters() function when submiting the info
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta charset="utf-8">
<title>MVC with XmlView</title>
<!-- Load UI5, select "blue crystal" theme and the "sap.m" control library -->
<script id='sap-ui-bootstrap'
src='https://sapui5.hana.ondemand.com/resources/sap-ui-core.js'
data-sap-ui-theme='sap_bluecrystal'
data-sap-ui-libs='sap.m'
data-sap-ui-xx-bindingSyntax='complex'></script>
<!-- DEFINE RE-USE COMPONENTS - NORMALLY DONE IN SEPARATE FILES -->
<!-- define a new (simple) View type as an XmlView
- using data binding for the Button text
- binding a controller method to the Button's "press" event
- also mixing in some plain HTML
note: typically this would be a standalone file -->
<script id="view1" type="sapui5/xmlview">
<mvc:View xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" controllerName="my.own.controller">
<Panel headerText="Filters">
<VBox>
<HBox>
<Label text="Filter by Customer:" class="sapUiSmallMarginTop sapUiSmallMarginEnd"/>
<ComboBox id="comboBox" selectedKey="{filtersModel>/customerFilter}">
<items>
<core:Item key="VINET" text="VINET" />
<core:Item key="TOMSP" text="TOMSP" />
<core:Item key="HANAR" text="HANAR" />
<core:Item key="VICTE" text="VICTE" />
<core:Item key="SUPRD" text="SUPRD" />
</items>
</ComboBox>
<Button text="Apply this Filter" press="_calculateFilters"></Button>
</HBox>
</VBox>
<VBox>
<HBox>
<Input value="{filtersModel>/shipAddressFilter}" id="input" submit="_calculateFilters" width="500px" placeholder="Filter by ShipAddress: Write and enter for filtering"/>
</HBox>
</VBox>
</Panel>
<Panel>
<List id="list" items="{/Orders}">
<StandardListItem title="{CustomerID}" info="{ShipAddress}"/>
</List>
</Panel>
</mvc:View>
</script>
<script>
// define a new (simple) Controller type
sap.ui.controller("my.own.controller", {
onInit: function(){
var oFiltersModel = new sap.ui.model.json.JSONModel();
sap.ui.getCore().setModel(oFiltersModel, "filtersModel");
},
_calculateFilters: function(){
var oSelect = this.getView().byId("comboBox"),
oListBinding = this.getView().byId("list").getBinding("items"),
oFiltersModel = sap.ui.getCore().getModel("filtersModel"),
oCustomerFilterValue = oFiltersModel.getProperty("/customerFilter"),
oShipAddressValue = oFiltersModel.getProperty("/shipAddressFilter"),
oFilters = [];
if(oCustomerFilterValue){
oFilters.push(new sap.ui.model.Filter("CustomerID", "EQ", oCustomerFilterValue));
}
if(oShipAddressValue){
oFilters.push(new sap.ui.model.Filter("ShipAddress", "Contains", oShipAddressValue));
}
oListBinding.filter(oFilters);
}
});
/*** THIS IS THE "APPLICATION" CODE ***/
// create some dummy JSON data
var data = {
actionName: "Say Hello"
};
// instantiate the View
var myView = sap.ui.xmlview({viewContent:jQuery('#view1').html()}); // accessing the HTML inside the script tag above
// create a Model and assign it to the View
var uri = "https://cors-anywhere.herokuapp.com/services.odata.org/Northwind/Northwind.svc"; // local proxy for cross-domain access
var oModel = new sap.ui.model.odata.ODataModel(uri, {
maxDataServiceVersion: "2.0"
});
myView.setModel(oModel);
// put the View onto the screen
myView.placeAt('content');
</script>
</head>
<body id='content' class='sapUiBody'>
</body>
</html>

Related

SAPUI5 Filter Bar Get filter values for each filter item in the filter bar

I have a filter bar with multiple filter items and I need to get the selected/typed values for each filter item in the onSearch event. I've tried but unable to figure out a way of getting all filter data for all the filter items.
<fb:FilterBar reset="onReset"
search="onSearchFilterbar"
showRestoreButton="true"
showClearButton="true"
filterBarExpanded="false"
id="userFilterBar">
<fb:filterItems>
<fb:FilterItem name="A" label="User">
<fb:control>
<Select id="slcUser" forceSelection="false"
items="{ path: 'sysusers>/Users' , sorter: { path: 'Name' } }" >
<core:Item key="{sysusers>Name}" text="{sysusers>Name}"/>
</Select>
</fb:control>
</fb:FilterItem>
<fb:FilterItem name="B" label="Location">
<fb:control>
<Select id="slcLocation" forceSelection="false"
items="{ path: 'location>/Locations' , sorter: { path: 'Name' } }">
<core:Item key="{location>Name}" text="{location>Name}"/>
</Select>
</fb:control>
</fb:FilterItem>
</fb:filterItems>
</fb:FilterBar>
onsearch:function(oEvent){
oEvent.getSource().getFilterItems()[0];
// But cannot find a way to get the selected data
}
there are a few ways to do this. IMO, the best way is to use model. that's adopting the MVC approach. here is a working example, http://jsbin.com/nudewew/edit?html,output
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="UTF-8">
<title>MVC</title>
<script id="sap-ui-bootstrap" type="text/javascript"
src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m,sap.ui.table"
data-sap-ui-xx-bindingSyntax="complex">
</script>
<script id="oView" type="sapui5/xmlview">
<mvc:View height="100%" controllerName="myView.Template"
xmlns="sap.m"
xmlns:fb="sap.ui.comp.filterbar"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc">
<fb:FilterBar reset="onReset"
search="onSearchFilterbar"
showRestoreButton="true"
showClearButton="true"
filterBarExpanded="false"
id="userFilterBar">
<fb:filterItems>
<fb:FilterItem name="A" label="User">
<fb:control>
<Select id="slcUser" forceSelection="false" selectedKey="{selection>/user}"
items="{ path: 'sysusers>/Users' , sorter: { path: 'Name' } }" >
<core:Item key="{sysusers>Name}" text="{sysusers>Name}"/>
</Select>
</fb:control>
</fb:FilterItem>
<fb:FilterItem name="B" label="Location">
<fb:control>
<Select id="slcLocation" forceSelection="false" selectedKey="{selection>/location}"
items="{ path: 'location>/Locations' , sorter: { path: 'Name' } }">
<core:Item key="{location>Name}" text="{location>Name}"/>
</Select>
</fb:control>
</fb:FilterItem>
</fb:filterItems>
</fb:FilterBar>
</mvc:View>
</script>
<script>
sap.ui.define([
'jquery.sap.global',
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel'
], function(jQuery, Controller, JSONModel) {
"use strict";
var oController = Controller.extend("myView.Template", {
onInit: function() {
var oView = this.getView();
oView.setModel(new JSONModel({
user: "",
location: ""
}), "selection");
oView.setModel(new JSONModel({
Users: [
{Name: "johnDoe"},
{Name: "maryAnn"}
]
}), "sysusers");
oView.setModel(new JSONModel({
Locations: [
{Name: "London"},
{Name: "Paris"}
]
}), "location");
},
onSearchFilterbar: function(oEvent) {
console.log(this.getView().getModel("selection").getData());
}
});
return oController;
});
var oView = sap.ui.xmlview({
viewContent: jQuery('#oView').html()
});
oView.placeAt('content');
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
The value of items is on Parameters of de Event.
oEvent.getParameter('0').selectionSet
It's a array with each Control of filterbar you can use:
oEvent.getParameter('0').selectionSet[0].getValue()
There are a few ways to do this.. but with your current code, I would suggest the following:
The short answer to your question:
The FilterBar has a method determineControlByFilterItem you can use to get the control for the filter item, which you can then use to get the selected value.
var oFilterItem = oEvent.getSource().getFilterItems()[0];
var oControl = oFilterBar.determineControlByFilterItem(oFilterItem);
var sSelectedValue = oControl.getSelectedKey();
Be cautious, though, when hard coding array indexes like this. For a more complete solution to your problem, I've suggested a full approach below.
The long answer if you want to use the filter bar to filter a result set:
First, make sure the names of your filter items align to the name of the property you want to filter by. So in your case, your filter items are named "A" and "B"... I suggest you change these to match the property name you want to filter by. Assuming that the names of the properties you want to filter by are "User" and "Location":
<FilterItem name="User" label="User">
...
<FilterItem name="Location" label="Location">
...
Then in your controller, you can use those names to build an array of sap.ui.model.Filter objects that you can use to filter your result set.
onSearch: function(oEvent) {
//get the filter bar from the event
var oFilterBar = oEvent.getSource();
//get the filter items from the filter bar
var aFilterItems = oFilterBar.getFilterItems();
//map the array of FilterItems to a new array of sap.ui.model.Filter objects
var aFilters = aFilterItems.map(function(oFilterItem) {
//get the filter item name (which is now the same as the filter property name)
var sFilterName = oFilterItem.getName();
//use the filter bar to get the control for the filter item
var oControl = oFilterBar.determineControlByFilterItem(oFilterItem);
//use the control to get the selected value (selected key)
var sSelectedValue = oControl.getSelectedKey();
//use the filter item/property name and the selected value to create a new sap.ui.model.Filter
var oFilter = new sap.ui.model.Filter(sFilterName, "EQ", sSelectedValue);
//return the Filter object to the new array
return oFilter
});
//use the array of sap.ui.model.Filter objects to filter your table
//if you're using a responsive table (sap.m.Table), use:
this.getView().byId("yourTableId").getBinding("items").filter(aFilters);
//or if you're using a grid table (sap.ui.table.Table), use:
this.getView().byId("yourTableId").getBinding("rows").filter(aFilters);
}
The reason I suggest this approach as opposed to others, is because it scales nicely. Say, for example, that you want to add a third Select control to filter by, you simply need to add a new <FilterItem name="NewFilterProperty" label="New Filter Property">. Because we didn't hard code anything into the event handler, it will still work without any additional changes.
The only thing to lookout for is if you use different types of controls in your FilterBar. So, for example, if you added an <Input> instead of a <Select>, you'll need to adjust the logic of your event handler to handle this.
I usually do something like this:
onSearch: function(oEvent) {
var oFilterBar = oEvent.getSource();
var aFilterItems = oFilterBar.getFilterItems();
var aFilters = aFilterItems.map(function(oFilterItem) {
var sFilterName = oFilterItem.getName();
var oControl = oFilterBar.determineControlByFilterItem(oFilterItem);
var sValue;
if (oControl.getMetadata().getName() === "sap.m.Select") {
sValue = oControl.getSelectedKey();
} else if (oControl.getMetadata().getName() === "sap.m.Input") {
sValue = oControl.getValue();
}
var oFilter = new sap.ui.model.Filter(sFilterName, "EQ", sValue);
return oFilter;
});
}

Is it possible to add Binding change event to a component in XML view?

I have a component in SAPUI5 where I need to listen to changes in the binding (Binding.change event). At the moment I'm adding a listener to the Binding in modelContextChange like this:
function onModelContextChange(oEvent){
var oSelect = oEvent.getSource();
var binding = oSelect.getBinding("items");
if(binding){
binding.attachChange(onDataChange, oSelect);
}
}
However this causes all kinds of weird problems, because modelContextChange could be fired multiple times. It would be better to to this in the XML view. I've tried code like this, but it doesn't work.
<Select items="{ path: 'project>/data/', change:'onDataChange' templateShareable: false">
<core:Item key="{project>Id}" text="{project>Parameter}"/>
</Select>
Any recommendations how to do this?
I just came across the problem, too. I solved it in that way:
<Select items="{
path: 'project>/data',
events: {
change: '.onDataChange'
},
templateShareable: false
}">
You can pass an events object to the binding and use the available bindings (e.g. v2.ODataListBinding). Note that you have to use a dot before your function name (.onDataChange). In your controller you can add the function:
onDataChange: function(oEvent) {
// Your implementation...
},
If I remember well from the JS Views, I think it is like this:
<Select items="{ path: 'project>/data/', events: {change:'onDataChange'}, templateShareable: false}">
This is for listening to the Model "change" events.
If you want to listen to the "change" event in the Select control, this is when the user selects a different value in the dropdown, it is like this:
<Select items="{ path: 'project>/data/', templateShareable: false}" change="onDataChange">
EDIT:
Using "modelContextChange" event.
<Select items="{ path: 'project>/data/', templateShareable: false}" modelContextChange="onDataChange">
here is an example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</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-xx-bindingSyntax="complex"
data-sap-ui-libs="sap.m"></script>
<style type="text/css">
.sapMObjLTitle {
cursor: pointer;
}
</style>
<!-- XML-based view definition -->
<script id="oView" type="sapui5/xmlview">
<mvc:View height="100%" controllerName="myView.Template"
xmlns="sap.m"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc">
<Select change="onDataChange" items="{ path: 'project>/data', templateShareable: false}">
<core:Item key="{project>Id}" text="{project>Parameter}"/>
</Select>
</mvc:View>
</script>
</head>
<body class="sapUiBody">
<div id='content'></div>
</body>
</html>
sap.ui.define([
'jquery.sap.global',
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel'
], function(jQuery, Controller, JSONModel) {
var ListController = Controller.extend("myView.Template", {
onInit: function(oEvent) {
var oView = this.getView();
oView.setModel(new JSONModel({
data: [{
Id: "1",
Parameter: "One"
}, {
Id: "2",
Parameter: "Two"
}]
}), "project");
},
onDataChange: function() {
alert("changed")
}
});
return ListController;
});
// Instantiate the View and display
var oView = sap.ui.xmlview({
viewContent: jQuery('#oView').html()
});
oView.placeAt('content');
https://jsbin.com/zufurav/edit?html,js,output
Note: the change attribute in your XML is incorrect
I managed to get the binding change event with this set to the element that I needed by attaching a modelContextChange to the element and handling attaching the change event to the binding in there. Here's the code from the view controller:
modelContextChange: function(oEvent) {
var oElement = oEvent.getSource();
var binding = oElement.getBinding("items");
if (binding) {
//Binding change event could already be attached, detach it first, if it's there
binding.detachChange(this.onBindingChange, oSelect);
binding.attachChange(this.onBindingChange, oSelect);
// Beacause I used this inside a sap.ui.table.Treetable,
// in some cases binding changes occur without the binding change event firing.
// Manually fire the binding change just in case
// YMMV
binding.refresh(true);
}
},
onBindingChange: function() {
//The code that needs to run at binding change
//"this" is set to the correct element
//I specifically needed to add one element in front of other items in a sap.m.Select
var items = this.removeAllItems();
this.addItem(new sap.ui.core.Item({
key: 0,
text: "< Inherit >"
}));
items.forEach(function(item) {
this.addItem(item);
}, this);
}

How to Make List Items Reorderable?

I have to create a table (sap.m.Table) in SAPUI5 where rows can be deleted, reordered, and clicked on to open a dialog. So far I've figured out that I can set the Table to mode="delete" and ColumnListItem to type="Navigation" to achieve deleting rows and clicking on rows to open dialogs at the same time:
Is it possible to add the functions to reorder rows to this?
You can use a "editModeEnabled" variable in your view model to change the Table mode to "SingleSelectLeft" and show/hide some buttons. Then in "editMode", use some buttons to insert and remove the items of the table wherever you want
Here a snippet
<html>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta charset="utf-8">
<title>MVC with XmlView</title>
<!-- Load UI5, select "blue crystal" theme and the "sap.m" control library -->
<script id='sap-ui-bootstrap' src='https://sapui5.hana.ondemand.com/resources/sap-ui-core.js' data-sap-ui-theme='sap_bluecrystal' data-sap-ui-libs='sap.m' data-sap-ui-xx-bindingSyntax='complex'></script>
<!-- DEFINE RE-USE COMPONENTS - NORMALLY DONE IN SEPARATE FILES -->
<!-- define a new (simple) View type as an XmlView
- using data binding for the Button text
- binding a controller method to the Button's "press" event
- also mixing in some plain HTML
note: typically this would be a standalone file -->
<script id="view1" type="sapui5/xmlview">
<mvc:View xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc" controllerName="my.own.controller">
<Page>
<Table id="myTable" mode="{= ${viewModel>/editModeEnabled} ? 'SingleSelectLeft' : 'SingleSelectMaster'}" items="{path:'json>/rows'}">
<headerToolbar>
<Toolbar>
<ToolbarSpacer></ToolbarSpacer>
<Button text="Edit" press="onEditPressed" visible="{= ${viewModel>/editModeEnabled} ? false : true}"></Button>
<Button icon="sap-icon://slim-arrow-down" press="onDownPressed" visible="{= ${viewModel>/editModeEnabled} ? true : false}"></Button>
<Button icon="sap-icon://slim-arrow-up" press="onUpPressed" visible="{= ${viewModel>/editModeEnabled} ? true : false}"></Button>
<Button text="Finish" press="onFinishEditPressed" visible="{= ${viewModel>/editModeEnabled} ? true : false}"></Button>
</Toolbar>
</headerToolbar>
<columns>
<Column>
<Text text="Column1" />
</Column>
<Column>
<Text text="Column2" />
</Column>
</columns>
<items>
<ColumnListItem>
<Text text="{json>col1}"></Text>
<Text text="{json>col2}"></Text>
</ColumnListItem>
</items>
</Table>
</Page>
</mvc:View>
</script>
<script>
// define a new (simple) Controller type
sap.ui.controller("my.own.controller", {
onInit: function(){
var oViewModelData = {
editModeEnabled: false
};
var oViewModel = new sap.ui.model.json.JSONModel();
this.getView().setModel(oViewModel, "viewModel")
},
onEditPressed: function() {
this.getView().getModel("viewModel").setProperty("/editModeEnabled", true);
},
onFinishEditPressed: function(){
this.getView().getModel("viewModel").setProperty("/editModeEnabled", false);
},
onUpPressed: function(oEvent){
var oSelectedItem = this.getView().byId("myTable").getSelectedItem();
var oCurrentIndex = this.getView().byId("myTable").indexOfItem(oSelectedItem);
if(oCurrentIndex > 0){
this.getView().byId("myTable").removeItem(oSelectedItem);
this.getView().byId("myTable").insertItem(oSelectedItem, oCurrentIndex-1);
}
},
onDownPressed: function(oEvent){
var oSelectedItem = this.getView().byId("myTable").getSelectedItem();
var oCurrentIndex = this.getView().byId("myTable").indexOfItem(oSelectedItem);
if(oCurrentIndex < this.getView().byId("myTable").getItems().length){
this.getView().byId("myTable").removeItem(oSelectedItem);
this.getView().byId("myTable").insertItem(oSelectedItem, oCurrentIndex+1);
}
}
});
/*** THIS IS THE "APPLICATION" CODE ***/
// create a Model and assign it to the View
//Using a small JSON model
var myData = {
rows: [
{
col1: "Row1Col1",
col2: "Row1Col2",
},{
col1: "Row2Col1",
col2: "Row2Col2",
},{
col1: "Row3Col1",
col2: "Row3Col2",
}
]
};
var oJSONModel = new sap.ui.model.json.JSONModel(myData);
// instantiate the View
var myView = sap.ui.xmlview({
viewContent: jQuery('#view1').html()
}); // accessing the HTML inside the script tag above
// Set the Models
myView.setModel(oJSONModel, 'json');
myView.placeAt('content');
</script>
</head>
<body id='content' class='sapUiBody'>
</body>
</html>

Object Page with blocks

I've got this ObjectPageLayout:
request.view.xml
<ObjectPageLayout>
<headerTitle>
...
</headerTitle>
<headerContent>
...
</headerContent>
<sections>
<ObjectPageSection
mode="Collapsed">
<subSections>
<ObjectPageSubSection title="fooBlock">
<blocks>
<blockdetail:FormBlock columnLayout="auto" /> <!-- MY BLOCK -->
</blocks>
</ObjectPageSubSection>
</subSections>
</ObjectPageSection>
</sections>
</ObjectPageLayout>
FormBlockCollapsed.view.xml (MY BLOCK)
<mvc:View xmlns:f="sap.ui.layout.form" xmlns:mvc="sap.ui.core.mvc"
xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout" xmlns="sap.m"
controllerName="NAMESPACE.blocks.DetailsBlockCommon">
<FlexBox>
<HBox>
<VBox>
<f:SimpleForm >
<f:content>
<CheckBox class="sapUiSmallMarginBegin sapUiSmallMarginTop" id="myCheckbox" />
</f:content>
</f:SimpleForm>
</VBox>
</HBox>
</FlexBox>
...
</mvc:View>
So far, everything is fine. My Object page looks good a the checkbox is shown.
In my Controller request.controller.js i want to validate the checkbox in FormBlockCollapsed.view.xml
validateBlockForm: function(format){
console.log( oView.byId("myCheckbox").checked() ); //oView.byId("myCheckbox") is undefined
}
But i've no access to my checkbox in the block.
Cannot read property 'checked' of undefined
Further infos
FormBlock.js
sap.ui.define(['sap/uxap/BlockBase'], function (BlockBase) {
"use strict";
var MultiViewBlock = BlockBase.extend("NAMESPACE.blocks.FormBlock", {
metadata: {
views: {
Collapsed: {
viewName: "NAMESPACE.blocks.FormBlockCollapsed",
type: "XML"
}
}
}
});
return MultiViewBlock;
}, true);
DetailBlockCommon.js
sap.ui.define([
"NAMESPACE/controller/BaseController"
], function (BaseController) {
"use strict";
return BaseController.extend("NAMESPACE.blocks.DetailsBlockCommon", {
});
});
You can access the elements in a section by having the block's id and element's id.
First we have to define an id for the block in the xml view:
<blocks>
<blockdetail:FormBlock id="formBlock" columnLayout="auto" /> <!-- MY BLOCK -->
</blocks>
Then we generate the id of the elements like the following in the view controller. The state of the art here is to add -Collapsed-- as part of the id that adds by SAPUI5 to sections elements.
var sFieldId = this.getView().createId("formBlock") +
"-Collapsed--myCheckbox";
var oCheckbox = sap.ui.getCore().byId(sFieldId);
Check if oView is defined.
you can easily get it by this.getView()

sap.m.List is not reacting to events

I have the following list, but it is not reacting to any of the events that I'm using.
In the method onSelectionChange i have breakpoints and is updating the label, but it is for some reason not reaching this. The onSearch method is working fine.
I'm using the sapui5
<mvc:View
height="100%"
controllerName="Tasks.CompletedTasks.view.CompletedTasks"
xmlns:l="sap.ui.layout"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m">
<SearchField
liveChange="onSearch"
width="100%" />
<Label id="label" text="test">
</Label>
<List
id="idList"
items="{/results}"
select="onSelectionChange"
>
<items>
<StandardListItem
title="{TaskTitle}"
description="{InstanceID}"
icon="sap-icon://task"
iconDensityAware="false"
iconInset="false"
/>
</items>
</List>
Code:
jQuery.sap.require("jquery.sap.resources");
jQuery.sap.require("sap.ui.model.Filter");
jQuery.sap.require("sap.ui.model.FilterOperator");
jQuery.sap.require("Tasks.CompletedTasks.util.ModelBuilder");
sap.ui.controller("Tasks.CompletedTasks.view.CompletedTasks", {
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* #memberOf cscompletedtasks.CompletedTasks
*/
onInit: function() {
//this.getView().bindElement("/results");
},
onSelectionChange : function (oEvt) {
var oList = oEvt.getSource();
var oLabel = this.getView().byId("label");
oLabel.setText("event");
},
onSearch : function (oEvt) {
// add filter for search
var aFilters = [];
var sQuery = oEvt.getSource().getValue();
if (sQuery && sQuery.length > 0) {
var filter = new sap.ui.model.Filter("TaskTitle", sap.ui.model.FilterOperator.Contains, sQuery);
aFilters.push(filter);
}
// update list binding
var list = this.getView().byId("idList");
var binding = list.getBinding("items");
binding.filter(aFilters, "Application");
}
});
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />
<script id="sap-ui-bootstrap"
src="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m"
data-sap-ui-xx-bindingSyntax="complex"
data-sap-ui-resourceroots='{"Tasks.CompletedTasks" : "./" }'>
</script>
<script>
new sap.ui.core.ComponentContainer( {
name : "Tasks.CompletedTasks"
}).placeAt("content");
</script>
</head>
<body class="sapUiBody" id="content">
</body>
</html>
The select event work if you set the mode of selection on the list.
<List
id="idList"
items="{/results}"
select="onSelectionChange",
mode="" //Type of mode you required SingleSelect,MultiSelect, Delete default it is None.
>
<items>
<StandardListItem
title="{TaskTitle}"
description="{InstanceID}"
icon="sap-icon://task"
iconDensityAware="false"
iconInset="false"
/>
</items>
</List>
refer this link for more information
Please slot this at the top of the function handling the onSelectionChange event:
jQuery.sap.log.setLevel(jQuery.sap.log.LogLevel['INFO']);
jQuery.sap.log.info("*** my onSelectionChange has triggered");
i.e.:
onSelectionChange : function (oEvt) {
jQuery.sap.log.setLevel(jQuery.sap.log.LogLevel['INFO']);
jQuery.sap.log.info("*** my onSelectionChange has triggered");
var oList = oEvt.getSource();
Then check the console of your browser and filter to find the output of this message. (Just in case the event is triggering and your consequent code doesn't do anything. (if you have set the LogLevel elsewhere please ignore)