Search field: Filtering nested object - sapui5

Hi all,
I have the following data structure :
[ {
"supplierCode": "supplier1",
"supplierDesc": "supplier1Desc",
"pos": [ {
"poNum": "11111",
"materialNum": "matNum11",
"materialDesc": "matDesc11"
},
{ "poNum": "11112",
"materialNum": "matNum22",
"materialDesc": "matDesc22"}
] },
{"supplierCode": "supplier2",
"supplierDesc": "supplier2Desc",
"pos": [ {
"poNum": "22222",
"materialNum": "matNum11",
"materialDesc": "matDesc11"},
{"poNum": "22223",
"materialNum": "matNum22",
"materialDesc": "matDesc22"}]
}
]
My task is to filter data in JSON model by properties in pos array.
I tried the following approach:
myList = this.getView().byId("myList");
var binding = myList.getBinding("items");
if (!query) {
binding.filter([]);
} else {
binding.filter([new sap.ui.model.Filter([
new sap.ui.model.Filter("supplierCode", sap.ui.model.FilterOperator.Contains, query),
new sap.ui.model.Filter("supplierDesc", sap.ui.model.FilterOperator.Contains, query),
new sap.ui.model.Filter("pos/materialDesc", sap.ui.model.FilterOperator.Contains, query)
], false)]);
}
with no luck.
Also, I found out it is possible to do with ODataModel, but I didn't find anything regarding JSONModel.
Can such filtering be done at all?
Thank you.

Here is an example on test function under the constructor of the Filter :
Filter result will return a line of list containing the materialDesc description introduced in the filter :
onFilterInvoices: function(oEvent) {
// build filter array
var aFilter = [];
var sQuery = oEvent.getParameter("query");
if (sQuery) {
aFilter.push(new sap.ui.model.Filter({
path: "pos",
test: function(oValue) {
var oMaterials = oValue;
for (var i in oMaterials) {
if (oMaterials[i].materialDesc === sQuery) {
return true;
}
}
return false;
}
}));
}
// filter binding
var oList = this.getView().byId("listapp");
var oBinding = oList.getBinding("items");
oBinding.filter(aFilter);
}

Related

How to initiate a var which will store array of values with different datatypes?

I have a dynamic expression built in .net, which works if the column type is string, however, if the column is date or int then i have to convert the input to the respective datatype before passing to the expression. How can I make it dynamic?
MemberExpression member = Expression.Property(param, filter.Name);
var propertyType = ((PropertyInfo)member.Member).PropertyType;
if (propertyType.GetType() == typeof(Int32))
{
var criteria = Array.ConvertAll(filter.Value, Int32.Parse);
}
else if (propertyType.GetType() == typeof(DateTime))
{
var criteria = Array.ConvertAll(filter.Value, DateTime.Parse);
}
else
{
var criteria = filter.Value;
}
criteria.Aggregate( // -- gives error here since criteria does not exist in current context
(Expression)Expression.Constant(false),
(acc, next) =>
Expression.MakeBinary(
ExpressionType.Or,
acc, Expression.Equal(member, Expression.Constant(next))));
I already tried defining
var criteria = null;
var criteria = object[];
dynamic criteria;
var criteria = new {};
Payload
{
"pageFilters": [
{
"name": "string",
"condition": "Equals",
"value": [
"string"
]
}
]
}

How to generate leaflet control from database

I wish to generate a custom dropdown filter, based on categories from a database.
How is this achieved?
In my example, this is (poorly) implemented with some hard coding and duplication.
var serviceOverlays = [
{name:"Cardiology", value:"cardiology"},
{name:"Opthamology", value:"opthamology"}
];
var oSelect = L.control({position : 'topright'});
oSelect.onAdd = function (map) {
var overlayParent = document.getElementById('new-parent'); // overlays div
var node = L.DomUtil.create('select', 'leaflet-control');
node.innerHTML = '<option value="cardiologist">Cardioligist</option><option value="opthamology">Opthamology</option>';
overlayParent.appendChild(node);
L.DomEvent.disableClickPropagation(node);
L.DomEvent.on(node,'change',function(e){
var select = e.target;
for(var name in serviceOverlays){
serviceOverlays[name].removeFrom(map);
}
serviceOverlays[select.value].addTo(map);
});
Fiddle
I created a Control for you:
L.Control.Select = L.Control.extend({
options: {
position : 'topright'
},
initialize(layers,options) {
L.setOptions(this,options);
this.layers = layers;
},
onAdd(map) {
this.overlayParent = L.DomUtil.create('div', 'leaflet-control select-control');
this.node = L.DomUtil.create('select', 'leaflet-control',this.overlayParent);
L.DomEvent.disableClickPropagation(this.node);
this.updateSelectOptions();
L.DomEvent.on(this.node,'change',(e)=>{
var select = e.target;
for(var value in this.layers){
this.layers[value].layer.removeFrom(map);
}
this.layers[select.value].layer.addTo(map);
});
return this.overlayParent;
},
updateSelectOptions(){
var options = "";
if(this.layers){
for(var value in this.layers){
var layer = this.layers[value];
options += '<option value="'+value+'">'+layer.name+'</option>';
}
}
this.node.innerHTML = options;
},
changeLayerData(layers){
this.layers = layers;
this.updateSelectOptions();
}
});
var oSelect = new L.Control.Select(serviceOverlays,{position : 'topright'}).addTo(map);
The data structure have to be:
var serviceOverlays = {
"cardiology": {name:"Cardiology", layer: cities},
"opthamology": {name:"Opthamology", layer: badCities}
};
Demo: https://jsfiddle.net/falkedesign/1rLntbo5/
You can also change the data dynamicl< with oSelect.changeLayerData(serviceOverlays2)

How to fetch people from a specific sharepoint group to ClientPeoplePicker in Sharepoint Online?

I have tried using ClientPeoplePickerSearchUser. Can anybody help me out? I have followed link : http://sharepointfieldnotes.blogspot.com/2014/06/sharepoint-2013-clientpeoplepicker.html
You need set "SharePointGroupID" property in the code to limit search people from a specific SharePoint group in client people picker.
function search(request,response) {
var appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
var hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var restSource = appweburl + "/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser";
var principalType = this.element[0].getAttribute('principalType');
$.ajax(
{
'url':restSource,
'method':'POST',
'data':JSON.stringify({
'queryParams':{
'__metadata':{
'type':'SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters'
},
'AllowEmailAddresses':true,
'AllowMultipleEntities':false,
'AllUrlZones':false,
'MaximumEntitySuggestions':50,
'PrincipalSource':15,
'PrincipalType': principalType,
'QueryString':request.term
//'Required':false,
'SharePointGroupID':23,
//'UrlZone':null,
//'UrlZoneSpecified':false,
//'Web':null,
//'WebApplicationID':null
}
}),
'headers':{
'accept':'application/json;odata=verbose',
'content-type':'application/json;odata=verbose',
'X-RequestDigest':requestDigest
},
'success':function (data) {
var d = data;
var results = JSON.parse(data.d.ClientPeoplePickerSearchUser);
if (results.length > 0) {
response($.map(results, function (item) {
return {label:item.DisplayText,value:item.DisplayText}
}));
}
},
'error':function (err) {
alert(JSON.stringify(err));
}
}
);
}

Not iterable when using find ObjectId

I'm trying to find a certain document in my mongodb then update the int value of it using find query, I'm using $in because I used an array to find each element inside it, but when I used ObjectId it gives me error:
bloodinventoryDocs is not iterable
Here is what I did
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('5c014c999cc48c3b0057988b');
var newValue = 1;
var newBloodgroup = "A_positive";
var newGetbloodcomponent = "Whole Blood";
Bloodinventory.find({ blood_component : { $in : newGetbloodcomponent} , blood_group: { $in :newBloodgroup},chapter: { $in :id}}, function(err, bloodinventoryDocs) {
for(let bloodinventory of bloodinventoryDocs) {
bloodinventory.num_stock = bloodinventory.num_stock + newValue ;
bloodinventory.save(function(err) {
if (err) {
console.log(err);
} else {
console.log('success');
}
});
}
});
Just use chapter: { $in: [id] }

NativeScript - how can I filter an observable array with SearchBar?

Hi I'm trying to filter an observable array of data fetched via a HTTP request on keypress of the SearchBar.
I managed to get the SearchBar property change to work but I can't seem to figure out what I'm doing wrong in the filtering logic.
Ideally I want to update the list as I type in the search term in the SearchBar. I've searched the API on the Telerik site, there wasn't really any examples I could find.
XML
<Page loaded="pageLoaded">
<ActivityIndicator busy="{{ isLoading }}" />
<ActionBar title="People">
</ActionBar>
<GridLayout>
<StackLayout>
<SearchBar id="searchBar" hint="Search for someone"></SearchBar>
<ListView items="{{ peopleList }}" itemTap="showDetail">
<ListView.itemTemplate>
<StackLayout>
<Label text="{{ fullName }}" horiztonalAlignment="left" verticalAlignment="center"></Label>
<Label text="{{ company }}" class="info"></Label>
</StackLayout>
</ListView.itemTemplate>
</ListView>
</StackLayout>
</GridLayout>
</Page>
JS
var frames = require("ui/frame");
var Observable = require("data/observable").Observable;
var PeopleListViewModel = require("../../shared/people-viewModel");
var activityIndicatorModule = require("ui/activity-indicator");
var page;
var userkey;
var peopleList = new PeopleListViewModel([]);
var pageData = new Observable({ peopleList: peopleList });
exports.pageLoaded = function(args) {
page = args.object;
page.bindingContext = pageData;
userkey = userkey || page.navigationContext.userkey;
peopleList.load(userkey); // fetch data from the backend
var searchBar = page.getViewById("searchBar");
searchBar.on("propertyChange", function (args) {
var searchText = args.object.text;
if (searchText === "") {
// NOT SURE WHAT TO DO HERE.
} else {
peopleList.filter(function (element, index, array) {
// DOESN"T WORK PROPERLY
console.log("element: ", JSON.stringify(element));
return element.fullName == searchText;
});
console.log("Text types: ", searchText);
}
});
};
exports.showDetail = function(args) {
var person = peopleList.getItem(args.index);
var navigateEntry = {
moduleName: "views/people/people-detail",
context: { person: person },
animated: false
};
frames.topmost().navigate(navigateEntry);
};
PeopleListViewModel.js
var config = require("./config");
var fetchModule = require("fetch");
var ObservableArray = require("data/observable-array").ObservableArray;
function PeopleListViewModel(people) {
var viewModel = new ObservableArray(people);
viewModel.load = function (userKey) {
return fetchModule.fetch(config.baseUrl + "/api/people/all/" + userKey)
.then(function (response) {
return response.json();
})
.then(function (data) {
data.forEach(function (person) {
viewModel.push(person);
});
}, function (error) {
console.log("Error: ", error);
});
};
viewModel.empty = function () {
while (viewModel.length) {
viewModel.pop();
}
};
return viewModel;
}
function handleErrors(response) {
if (!response.ok) {
console.log("Error occurred");
}
}
module.exports = PeopleListViewModel;
Updated people-list
var frames = require("ui/frame");
var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;
var PeopleListViewModel = require("../../shared/people-viewModel");
var activityIndicatorModule = require("ui/activity-indicator");
var page;
var userkey;
var peopleList = new PeopleListViewModel([]);
var pageData = new Observable({ peopleList: peopleList });
var resultList = new ObservableArray([]);
exports.pageLoaded = function(args) {
page = args.object;
page.bindingContext = pageData;
userkey = userkey || page.navigationContext.userkey;
peopleList.load(userkey);
var searchBar = page.getViewById("searchBar");
searchBar.on("propertyChange", function (args) {
var searchText = args.object.text;
if (searchText === "") {
} else {
while (resultList.length > 0) {
resultList.pop();
}
peopleList.forEach(function (element) {
if (element.fullName === searchText) {
resultList.push(element);
}
});
}
});
};
I had the same issue. If you want to filter your data after every character has changed in search-bar you can try my solution.
Definitions
My playerList is your peopleList. This is the data from view-model.
resultList is an array where the data will be pushed.
var observableArrayModule = require("data/observable-array").ObservableArray;
var playerList = new PlayerListViewModel([]);
var resultList = new observableArrayModule([]);
var pageData = new observableModule.Observable({
resultList: resultList,
player: ""
});
Inside expors.loaded()
page = args.object;
searchBar = page.getViewById("search-bar");
page.bindingContext = pageData;
Load Initial Data - inside expors.loaded()
We are loading initial data when user navigates to the screen for the first time. We are also pushing the same data to resultList since we are using {{resultList}} in xml. You can add loadingIndicator while the list is populated.
playerList
.load()
.then(function() {
setTimeout(function() {
playerList.forEach(function (element) {
pageData.resultList.push(element);
});
}, 1000);
})
.catch(function(error) {
dialogsModule.alert({
message: "An error occurred while loading players.",
okButtonText: "OK"
});
});
Clear autofocus - inside expors.loaded()
This is to prevent keyboard from opening on initial screen navigation.
if (searchBar.ios) {
searchBar.ios.endEditing(true);
} else if (searchBar.android) {
searchBar.android.clearFocus();
}
Search data when character has changed - inside expors.loaded()
I am calling filter functionality. Lodash _.debounce function is used to delay looping through resultList array. Without it, the app would loop every time letter is typed. Now we are waiting for user to stop typing to start looping.
searchBar.on('propertyChange', _.debounce(searchList, 500));
searchList Function
This is the actual loop. You can change element.name for your needs.
function searchList(args) {
var searchText = args.object.text;
while(resultList.length > 0) {
resultList.pop();
}
playerList.forEach(function (element) {
if (element.name.toLowerCase().indexOf(searchText) >= 0) {
resultList.push(element);
}
});
}
Hide keyboard if search-bar is cleared - inside exports.loaded()
And finally we want to hide the keyboard if user clears the search-bar.
searchBar.on(searchBarModule.SearchBar.clearEvent, function (args) {
setTimeout(function() {
searchBar.dismissSoftInput();
}, 10);
});
PS
You probably solved your issue, but this could help someone else in the future.
Okay so your problem is a Javascript problem than a NativeScript problem. For the sake of this problem, think of observable arrays as just your ordinary arrays.
In your JS you're creating a new PeopleListViewModel which you're then attaching to the bindingContext via the pageData object. So far so good. Then you're calling the load method on the PeopleListViewModel (It returns a promise which you're not really doing anything with but for this specific problem it doesn't matter).
However, when text is inputed you're not really doing anything. This is your code:
peopleList.filter(function (element, index, array) {
// DOESN"T WORK PROPERLY
console.log("element: ", JSON.stringify(element));
return element.fullName == searchText;
});
peopleList is an instance of PeopleListViewModel which returns an ObservableArray. The ObservableArray does indeed have a method called filter (which works just like filter of a regular array. Check out the NativeScript documentation and Javascript documentation of filter).
What you need to understand here is that filter returns a new array with the filtered results. Doing peopleList.filter() will send that new array into empty space. You want to var yourNewFilteredArray = peopleList.filter(). But you don't really want to redefine the array bound to the binding context, you want to modify the content of it.
Here's an example of how you could do that:
/*
* Attach a new obsersable array to the binding context.
* you can prepopulate it with the data from the
* PeopleListViewModel if you want to
*/
var resultList = new ObservableArray([]);
var pageData = new Observable({ resultList: resultList });
/*
* Then on search/filter you want to modify this new
* array. Here I first remove every item in it and then
* push matching items to it.
*/
searchBar.on("propertyChange", function (args) {
var searchText = args.object.text;
// ...
while(resultList.length > 0) {
resultList.pop();
}
peopleList.forEach(function (element) {
if (element.fullName === searchText) {
resultList.push(element);
}
});
});