Read OData Service and rebind List - data-binding

I have a List, bound to an entityset from mainService. Same view contains a filter field. Once user enters some filtering criteria, the read should happen. I am already reading the OData entityset, results are coming back. But I have no luck to let the table be bound to that result
The binding in XML View
<List
id="list"
width="auto"
class="sapFDynamicPageAlignContent"
items= "{/ItProjHeadSet}"
busyIndicatorDelay="{masterView>/delay}"
noDataText="{masterView>/noDataText}"
mode="{= ${device>/system/phone} ? 'None' : 'SingleSelectMaster'}"
growing="true"
growingScrollToLoad="true"
updateFinished=".onUpdateFinished"
selectionChange=".onSelectionChange">
Then, when the GO button of the smart filter bar is clicked, I am triggering the onSearch event as follows:
onSearchProjects : function (oEvent) {
var oMasterPage = this.getView().byId("masterPage");
var that = this;
var aTokens = this._oMultiInput.getTokens();
var aMultiFilters = aTokens.map(function (oToken) {
var oProperties = oToken.data("range");
return new Filter({
path: oProperties.keyField,
operator: FilterOperator[oProperties.operation],
value1: oProperties.value1,
value2: oProperties.value2
});
});
oMasterPage.setBusy(true);
//Filter
this.getOwnerComponent().getModel().read("/ItProjHeadSet", {
filters: aMultiFilters,
success: function (oData) {
var list = that.getView().byId("list");
var projectModel = new JSONModel(oData);
var oModel = that.getView().getModel("/ItProjHeadSet");
oModel.setData(projectModel);
oModel.updateBindings(true);
error: function (oData) {
MessageToast.show(that.getResourceBundle().getText("noProjectsFetched"));
}
});
oMasterPage.setBusy(false);
},
The problem then is that although I am receiving the corresponding successful results in the read, the setData seems that it is happening to a different model than the one bound to the list.
Am I doing the right model update in the Success read?
Regards,
Martin

Solved by my own, by getting the list binding then applying filters:
List.getBinding("items").filter(aMultiFilters, "Application");
then there was no need to getOwnerComponent and all that

Related

Fullcalendar, Resources as function don't work

I'm working with Fullcalendar and I'm trying to get resources as function
resources: function(callback){
var manageEvent = new ManageEvent();
var request = manageEvent.getEmployees();
request.always(function (param) {
//location.reload();
var list = [];
var emp;
for (var elem in param) {
emp = param[elem];
list.push({
'id': emp['cp_collaboratore'],
'title': emp['cognome_col']
});
}
var t = JSON.stringify(list);
callback(t);
});
request.catch(function (param) {
alert('errore');
});
},
I checked the variable 't' through log and it shows the following result:
[{"id":"1","title":"name_1"},{"id":"2","title":"name_2"},{"id":"3","title":"name_3"},{"id":"5","title":"name_4"},{"id":"9","title":"name_5"}]
but it don't works and shows the following error message:
Uncaught TypeError: resourceInputs.map is not a function
at ResourceManager.setResources
You just need to write
callback(list);
t in your code is a string, because you converted your list array into a string using JSON.stringify(). But fullCalendar expects an actual array, not a string. It can't run functions or read individual properties from a string.
You can remove the line var t = JSON.stringify(list); completely, it's not needed.
Generally the only reason you'd use stringify() is if you wanted to log the value to your console for debugging, or convert the array into JSON if you wanted to send it somewhere else using AJAX. It makes no sense to pass arrays and objects around inside JavaScript as serialised strings, when you can just use the objects themselves.

Search multiple field in MongoDB with MeteorJS

I am beginner in programming and interested to learn MeteorJS. I want to search category_name and subcategory_name by keyword or alphabet.:)
This is my code.
collections: subcategory
{
_id:"ZbwCsJEMi2DesyJA7",
category_name: "ICT",
subcategory_name: "Laptop"
}
subcategory.js
Template.Subcategory.events({
"keyup .searchbox": function(event){
var query = event.target.value;
Session.set('query', query);
}
});
Template.Subcategory.helpers({
subcategory: function(){
var filter = {sort: {}};
var query = Session.get('query');
filter.sort[Session.get('sortby')] = 1;
return Subcategory.find({ subcategory_name: new RegExp(query, 'i')} , filter );
}
});
Seems like you are looking for $or operator:
var queryRegexp = new RegExp(query, 'i');
return Subcategory.find({
$or: [
{ category_name: queryRegexp },
{ subcategory_name: queryRegexp }
]
} , filter);
Official Mongo's documentation for $or: https://docs.mongodb.org/manual/reference/operator/query/or/
You'll have to create a text index in Mongo. You can do this in Meteor still I think with something like this:
MyCollection._ensureIndex({
"$**": "text"
});
The above uses a wildcard but you can be more specific. See https://docs.mongodb.org/v3.0/core/index-text/ for more info.
For larger collections I tend to pass a text search query through a subscriptions so it can be performed on the server.
Assuming you want to show a list of things and allow users to filter them with the search box, you could do something like this:
Meteor.publish('MyCollection', function (searchTerm) {
return searchTerm ? MyCollection.find() : MyCollection.find({ $text: {$search: searchTerm} });
});
On the client, assuming you're using template-level subscriptions, you could set up your subscription like this:
Template.Subcategory.onCreated(function(){
var self = this;
// requires the reactive-var package
self.searchTerm = new ReactiveVar(false);
self.autorun(function(){
self.subscribe( "MyCollection", self.searchTerm.get() );
});
});
It'd then just be a case of setting your search term:
Template.Subcategory.events({
'keyup .searchbox': function(e,t){
var inputValue = e.currentTarget.value,
//you could set an arbitrary minimum search term length like so
searchTerm = inputValue.length > 1 ? inputValue : false;
t.searchTerm.set(searchTerm);
}
});
There's a couple of caveats on relying on the subscriptions so heavily like this. For example, if your collections are scoped globally on the client you run the risk of multiple subscriptions to the same collection giving you results you might not want to render within your list. Nevertheless, I quite like this approach. Food for thought.

KendoUI read() and query() datasource methods inconsistencies

On a button click I need to read the first page of my data. The common answer is to use the query() method of datasource, specifing page, and other additional values through the parameterMap. The problem is that in my datasource I am also using aggregates, and the query() methods does not seem to handle them at all.
Am I right? Is it because only read() uses "transport.read" settings?
Is there another way to reset a grid binded to a datasource to the first page mantaining all datasource settings?
Yep mate there is specific method for paging -> dataSource.page(3). Here is link from the documentation.
I solved my problem (read the first page of data through datasource, with parameters) using "datasource.page(1)" and setting the values in the parameterMap through an "observable" object, so they are updated when I change my parameters and sent through the "page(1)" request.
=== JAVASCRIPT ===
var vm = kendo.observable({
param1: "value1",
param2: "value2",
param3: "value3"
});
var datasource = new kendo.data.DataSource({
transport: {
parameterMap: function (inputParams, operation) {
return JSON.stringify($.extend({
param1: vm.get("param1"),
param2: vm.get("param2"),
param3: vm.get("param3"),
));
}
}
});
$("#btn").bind("click", function(e) {
// set call parameters, if needed
vm.set("param1", "new value");
datasource.page(1);
});
=== HTML ===
<button class="k-button" id="btn">GetData</button>

rebind properties in model, emberjs

I have just started to use ember.js. I have two models in my application. One that holds data and one that holds this data edited by user. I bind them using one-way binding.
App.ViewModel = Ember.Object.create({
title:'title',
text:'text',
)};
App.EditModel = Ember.Object.create({
titleBinding: Ember.Binding.oneWay('App.ViewModel.title'),
textBinding: Ember.Binding.oneWay('App.ViewModel.text'),
)};
I let a user edit the data in EditModel model. But if the user discard the changes I want to be able to set the values back to the state before editing, ie. to the values in ViewModel.
Is there a way to rebind those properties? Or to manualy rise change event on properties in ViewModel so EditModel gets updated? Or any other approach to my problem?
You could create a custom Mixin which handles the reset for a model, see http://jsfiddle.net/pangratz666/CjB4S/
App.Editable = Ember.Mixin.create({
startEditing: function() {
var propertyNames = this.get('propertyNames');
var props = this.getProperties.apply(this, propertyNames);
this.set('origProps', props);
},
reset: function() {
var props = this.get('origProps');
Ember.setProperties(this, props);
}
});
App.myModel = Ember.Object.create(App.Editable, {
propertyNames: ['title', 'text'],
title: 'le title',
text: 'le text'
});
And later in the views you just invoke the startEditing when you want to take a snapshot of the current values and reset when you want to reset to the previous snapshot of the values.

How do i bind the json data to a asp.net dropdownlist using jquery?

I am trying to design a cascading dropdown. i am using 3 asp.net dropdowns. THe first one on page load loads the countries. Then when a country is selected i do a ajax call to a webmethod. I fetch the data for the teams belonging to that country. The data is in a dataset which i convert into JSON and then return it. On success what code do i need to add to bind the json data to the dropdown list.
below is the code.
$(document).ready(function() {
$('#ddlcountries').change(function() {
debugger;
var countryID = $('#ddlcountries').val();
$.ajax({
type: "POST",
url: "Default.aspx/FillTeamsWM",
data: '{"CountryID":' + countryID + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(jsonObj) {
/* WHAT CODE DO I ADD HERE TO BIND THE JSON DATA
TO ASP.NET DROP DOWN LIST. I DID SOME GOOGLING
BUT COULD NOT GET PROPER ANSWER */
},
error: function() {
alert('error');
}
});
});
});
Depending on what you're passing back to the client, I am going to assume it's a List<string>. You can adjust the code accordingly depending on what you're passing back to the client, since you're not telling us what is being passed back.
So if that is the case do something like this:
// first remove the current options if any
$('#ddlTeams').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(jsonObj).each(function(index, item){
$('#ddlTeams').append($('<option></option>').val(item).html(item));
});
Assuming again, if your List has an object containing teamid and `teamname11
// first remove the current options if any
$('#ddlTeams').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(jsonObj).each(function(index, item){
$('#ddlTeams').append($('<option></option>').val(item.teamid).html(item.teamname));
});
It is dependent on the data you are getting back from the server but this is what I came up with presuming it was a simple json structure, I was also wondering whether it may be better to send the data on the first request, and forget about the ajax.
$('#continent').change(function() {
// success function
$('#country').children().remove();
for (var country in json.continents[$(this).val()]) {
var $elm = $('<option>').attr('value', country)
.html(country);
$('#country').append($elm);
}
})
Here is a demo;
Edit: Given your data structure have update so something like this
var teams = json['TeamList'];
$('#teamid').change(function() {
// success function
var $t = $(this);
var $select = $('#teamname');
var i = (function() {
for (var i=0; i<teams.length; i++) {
if (teams[i]['teamid'] == $t.val()) {
return i;
}
}
})()
var name = teams[i]['teamname'];
var $elm = $('<option>').val(name).html(name);
$select.children().remove();
$select.append($elm);
})
see here for demo, please note this may requiring some changing to fit your specific use case, but it demonstrates simple iteration over arrays and objects

Resources