This is my code in controller init method:
mycontroller = this
var data = [{
"No": "456980",
"Updates": [{
"Test": "abc"
}, {
"Test": "bca"
}, {
"Test": "dbd"
}]
}, {
"No": "456980",
"Updates": [{
"Test": "abc"
}, {
"Test": "bca"
}, {
"Test": "dbd"
}]
}, {
"No": "456980",
"Updates": [{
"Test": "abc"
}, {
"Test": "bca"
}, {
"Test": "dbd"
}]
}]
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
//set this model to list control having custom list as aggregation
mycontroller.List1.setModel(oModel);
mycontroller.List1.bindAggregation("items", {
path: "/",
template: mycontroller.List1_template
});
var ListItems = P1Notificationcontroller.list1.getItems();
var ListLength = ListItems.length;
for (var i = 0; i < ListLength; i++) {
var control = "status_vbox-list1-" + i;
sap.ui.getCore().byId(control).bindAggregation("items", {
path: "Updates",
template: new sap.m.Text('', {
text: '{Update}'
})
});
}
view declaration create content
oController.List1 = new sap.m.List("List1", {
headerDesign: sap.m.ListHeaderDesign.Standard
});
oController.List1_template = new sap.m.CustomListItem("McustomlistItem", {
content: [
new sap.m.VBox('', {
items: [
new sap.m.Text('', {
text: "{No}"
})
new sap.m.VBox('status_vbox', {
items: []
})
]
}));
The above code in view and controllers init method works perfectly fine the items in custom list VBox are aggregated from update array in data.
when the same data when maintained in local json file &
by using this line of code
var jsonmodel = new sap.ui.model.json.JSONModel("mockData/local.json");
mycontroller.List1.setModel(jsonmodel)
the loop for VBox is failing because we are not able to loop the object .
when i console.log of both models OData attribute of one model is showing as Array and other as object, because of object the loop is not happening
how can we maintain the same data in local json file to loop the updates attribute to the VBox in custom list item as above.
the issue resolved by calling jquery ajax call to fill the local json model as below
jQuery.ajax({
url: "mockData/Local.json",
dataType: "json",
success: function(data, textStatus, jqXHR) {
var jsonmodel = new sap.ui.model.json.JSONModel();
jsonmodel.setData(data);
sap.ui.getCore().setModel(jsonmodel,'testmodel');
mycontroller.List1.setModel(jsonmodel)
}
Related
I am developing of a SAPUI5 application, in my application I need to pass data from one View1 to View2. I follow some sample code from internet but it seems like does not work for me.
The following is my source code
View1.controller.js
onShoppingCartPressed: function(){
var viewCartData = {
"Customer" : SelectedCustomer,
"Salesman" : SelectedSalesman,
"TxnKey" : "TXN1000103"
};
this._oRouter.navTo("ViewCarts", viewCartData);
}
View2.controller.js
onInit: function () {
this._oRouter.getRoute("ViewCarts")
.attachMatched(this._onRouteMatched, this);
},
_onRouteMatched: function(oEvent) {
console.log(oEvent.getParameter("arguments"));
},
Manifest.json
"routing": {
"config": {
"routerClass": "sap.f.routing.Router",
"viewType": "XML",
"viewPath": "com.accenture.newspage.order.ui.order-ui.view",
"controlId": "flexibleColumnLayout",
"transition": "slide",
"controlAggregation": "beginColumnPages",
"bypassed": {
"target": [
"notFound"
]
},
"async": true
},
"routes": [
{
"pattern": "orderDetail/{order}/{layout}",
"name": "orderDetail",
"target": [
"order",
"orderDetail"
]
},
{
"pattern": "ViewCarts",
"name": "ViewCarts",
"target": "viewCarts"
}
],
"targets": {
"worklist": {
"viewName": "Worklist",
"viewId": "worklist",
"viewLevel": 1
},
"viewCarts": {
"viewName": "ViewCart",
"viewId": "ViewCartPage",
"viewLevel": 1
}
}
}
When I console.log() out the data, it shows me empty data and it does not show the data that I passed from View1.
You seem to have two options here in my option. Correct me if I'm wrong.
Hope this helps.
Option 1
Manifest
{
"pattern": "ViewCarts/customer/{Customer}/Salesman/{Salesman}/key/{TxnKey}",
"name": "ViewCarts",
"target": "ViewCarts"
}
Sending controller
onShoppingCartPressed: function(oEvent) {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("viewCarts", {
Customer: "XXXXXXXXXXXX", // can't be an object
Salesman: "xxxxxxxxxxxx",
TxnKey : "TXN1000103"
});
}
Receiving controller
onInit: function() {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.getRoute("viewCarts").attachMatched(this._onRouteMatched, this);
},
_onRouteMatched: function(oEvent) {
var customer = oEvent.getParameter("arguments").Customer;
var salesman = oEvent.getParameter("arguments").Salesman;
var key = oEvent.getParameter("arguments").TxnKey;
}
Option 2
Manifest
No changes from yours
Sending controller
onShoppingCartPressed: function(oEvent) {
var viewCartData = {
"Customer": "XXXXXXXXXXXX",
"Salesman": "xxxxxxxxxxxx",
"TxnKey": "TXN1000103"
};
var oModel = new sap.ui.model.json.JSONModel(viewCartData);
this.getOwnerComponent().setModel(oModel, "viewCartData");
// OR sap.ui.getCore().setModel(oModel, "viewCartData");
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("viewCarts");
}
Receiving controller
onInit: function() {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.getRoute("viewCarts").attachMatched(this._onRouteMatched, this);
},
_onRouteMatched: function(oEvent) {
var oModel = this.getView().getModel("viewCartData");
// OR var oModel = sap.ui.getCore().getModel("viewCartData");
}
For me in most scenarios it's better to use sessionStorage.
It allows you to save almost anything (also javascript Object) and access it anywhere in webapp.
sessionStorage.setItem('myKeyString', 'myString'); //Set value
sessionStorage.getItem('myKeyString'); // Get saved string
sessionStorage.setItem('myObject', JSON.stringify({"key": "value"})); // Save object
JSON.parse(sessionStorage.getItem('myObject')); // Get saved object
I'm building an app with AppceleratorStudio with alloy database. I have used also backbone to access the data.
So I have a problem if I try to update a data on database.
This is my code:
var _model = Alloy.createModel("AlertDAO", {
ID: null,
IdOmnia : obj.id_omnia,
Code: obj.info.code,
CodeSystem: obj.info.code_system,
DisplayName: obj.info.displayName,
DisplayNameTarget: obj.info.displayNameTarget,
StartDate: obj.date_start,
EndDate: obj.date_end,
CodeStatus: obj.alarm_alert_info.code,
CodeSystemStatus: obj.alarm_alert_info.code_system,
DisplayNameStatus: obj.alarm_alert_info.displayName,
DisplayNameTargetStatus: obj.alarm_alert_info.displayNameTarget,
Observation: ""
});
//I check if the recors exist on database
var alert = db_alert.getAlert(null,_model.attributes.IdOmnia);
if(alert!=undefined){
//update
_model.attributes.ID = alert.attributes.ID;
Titanium.API.info("MODEL DOPO AGGIORNAMENTO ID: "+_model.attributes.ID);
_model.save();
Titanium.API.info("ALERT AGGIORNATO con ID: "+ _model.attributes.ID);
}else{
//sul database non esite.
_model.save();
Titanium.API.info("ALERT SALVATO con ID: "+ _model.attributes.ID);
}
with this code I create a "_model" with the data, next I check if that ID is also saved in local database. If it is just save I should update the data.
Then the problem is on that line code:
_model.attributes.ID = alert.attributes.ID;
Titanium.API.info("MODEL DOPO AGGIORNAMENTO ID: "+_model.attributes.ID);
_model.save();
Titanium.API.info("ALERT AGGIORNATO con ID: "+ _model.attributes.ID);
the first message print ID=1, after the save, ID = 2 grrrr
How can I update all field but not add next row, but update the row??
This is the model.
exports.definition = {
config: {
columns: {
"ID": "INTEGER PRIMARY KEY AUTOINCREMENT",
"IdOmnia": "INTEGER",
"Code": "text",
"CodeSystem": "text",
"DisplayName": "text",
"DisplayNameTarget": "text",
"StartDate": "text",
"EndDate": "text",
"CodeStatus": "text",
"CodeSystemStatus": "text",
"DisplayNameStatus": "text",
"DisplayNameTargetStatus": "text",
"Observation": "text"
},
adapter: {
type: "sql",
collection_name: "AlertDAO",
idAttribute: "ID"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
// extended functions and properties go here
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
destroyAll : function(opt) {
var db = Ti.Database.open(this.config.adapter.db_name);
db.execute("DELETE FROM " + this.config.adapter.collection_name);
db.close();
this.models = [];
if (!opt || !opt.silent) { this.trigger("reset"); }
return this;
}
});
return Collection;
}
};
I'm new to Meteor and trying to figure out this issue I have.
I'm trying to load data from the Lessons collection based on the route being passed. e.g if /courses/level1/lesson1/1a is passed then show data
Unfortunately this doesn't work.
Am I on the right path or is there a better way of doing this?
Collection
{
"_id": "YSgr3fvjpEBn7ncRa",
"courseId": "level1",
"lesson": [
{
"lessonId": "lesson1",
"freeLesson": true,
"title": "Lesson 1",
"eachLesson": [
{
"eachLessonId": "1a",
"title": "This is (masculine)",
"video": "839843"
},
{
"eachLessonId": "1b",
"title": "That is (masculine)",
"video": "839843"
},
{
"eachLessonId": "1c",
"title": "This is (feminine)",
"video": "839843"
},
{
"eachLessonId": "1d",
"title": "That is (feminine)",
"video": "839843"
},
{
"eachLessonId": "1e",
"title": "Getting to know you",
"video": "839843"
}
]
}
]
}
Routes
Router.route("courses/:courseId/:lessonId/:eachLessonId", {
path:"/courses/:courseId/:lessonId/:eachLessonId",
layoutTemplate: "layoutLessons",
template:"lessons",
onBeforeAction:function(){
var currentUser = Meteor.userId();
if (currentUser) {
Session.set('courseId', this.params.courseId);
Session.set('lessonId', this.params.lessonId);
Session.set('eachLessonId', this.params.eachLessonId);
this.next();
} else {
Router.go('/')
}
},
});
Template helper
Template.lessons.onCreated(function(){
Meteor.subscribe('listLessons');
});
Template.lessons.helpers({
currentLesson: function() {
var currentLesson = Session.get('eachLessonId');
return Lessons.find({"lesson.eachLesson.eachLessonId" : currentLesson});
},
});
HTML
{{#each currentLesson}}
{{title}}
{{video}}
{{/each}}
Instead of storing courseId, lessonId and eachLessonId as Session values, you could use the Iron Router's waitOn and data option.
For example, you could rewrite your route as follows:
Router.route('/courses/:courseId/:lessonId/:eachLessonId', {
name: 'lessons',
layoutTemplate: 'layoutLessons',
template: 'lessons',
onBeforeAction: function() {
let currentUser = Meteor.user();
if (currentUser) this.next();
else Router.go('/');
},
data: function() {
var doc = Lessons.findOne({
"courseId": this.params.courseId,
"lesson.lessonId": this.params.lessonId,
"lesson.eachLesson.eachLessonId": this.params.eachLessonId
});
if (doc) {
var lesson = {};
var lessonId = this.params.eachLessonId;
_.each(doc.lesson, function(i) {
lesson = _.find(i.eachLesson, function(j) {
return j.eachLessonId == lessonId;
});
});
return lesson;
}
return {};
},
waitOn: function() {
return [
Meteor.subscribe('lesson', this.params.courseId, this.params.lessonId, this.params.eachLessonId)
];
}
});
This should set the data context to the requested eachLesson object. However, you may consider setting the data context to a document in the Lessons collection and then just picking certain eachLesson objects. In addition, you should create a publish function which returns just the requested Lessons document and not all of them, like you probably do now in your listLessons publication. You can pass all IDs as arguments to the corresponding publish function.
I am trying to filter results using Typeahead.js. I can currently filter the results using a field called activity_title. This works fine.
How can I filter my results by a second value? In this case, I would like to select only the results that have a certain value for activity_level. I need to set this when the typeahead is initialised rather than hard coding it into the Bloodhound initialisation (e.g. I don't want to use url: 'api/activity/&range=1,3')
I have the following valid JSON that I access remotely:
{
"meta": [
{
"name": "activity_id",
"table": "table",
"max_length": 4
},
{
"name": "activity_title",
"table": "table",
"max_length": 91
},
{
"name": "activity_level",
"table": "table",
"max_length": 2
}
],
"detail": [
{
"activity_id": "57",
"activity_title": "Help old ladies to cross the road.",
"activity_level": "2"
},
{
"activity_id": "58",
"activity_title": "Help mum with the washing up.",
"activity_level": "3"
},
{
"activity_id": "59",
"activity_title": "Shine my shoes",
"activity_level": "1"
},
{
"activity_id": "60",
"activity_title": "Put the bins out",
"activity_level": "1"
}
]
}
I set up a Bloodhound instance like this:
var activities = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.activity_title);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: '/api/activity/',
filter: function(data) {
return $.map(data['detail'], function(detail) {
return {
activity_id: detail.activity_id,
activity_title: detail.activity_title,
objective_level: detail.objective_level
};
});
}
}
});
I use Typeahead.js to do a lookup on the data as I type.
$( document ).on( "focus", ".typeahead-init", function() {
// + '&range=' + minimum + ',' + maximum
var minimum = $('#group-level-min-1').val();
var maximum = $('#group-level-max-1').val();
$(this).typeahead({
highlight: true
},
{
name: 'activity_title',
displayKey: 'activity',
source: activities.ttAdapter(),
templates: {
header: '<div class="header-name">Activities</div>',
empty: [
'<div class="empty-message">',
'No activities match your search',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<div class="typeahead-activity" id="typeahead-activity-{{activity_id}}"><strong>{{objective_level}}</strong> - {{activity_title}}</div>')
}
})
//info on binding selection at https://github.com/twitter/typeahead.js/issues/300
.bind('typeahead:selected', function(obj, datum, name) {
var target = $(this).closest('.activity-container');
var activityId = datum['activity_id'];
var url = '/api/activity/id/'+activityId;
$(target).children('.activity-id').val(activityId);
//http://runnable.com/UllA9u8MD5wiAACj/how-to-combine-json-with-handlebars-js-for-javascript-ajax-and-jquery
var raw_template = $('#activity-output').html();
// Compile that into an handlebars template
var template = Handlebars.compile(raw_template);
// Fetch all data from server in JSON
$.get(url,function(data,status,xhr){
$.each(data,function(index,element){
// Generate the HTML for each post
var html = template(element);
// Render the posts into the page
target.append(html);
});
});
});
$(this).removeClass("typeahead-init");
$(this).focus();
});
This has been cobbled together from several answers on Stackoverflow and others. Any help greatly appreciated.
I'm trying to build some foundations for a single page web app in Backbone.js. I've structured my JSON into "screens", with each screen being given an ID.
I would like to be able to render data from specific screens, both for the initial page load, and also after on.click events.
I've been trying to pass in an ID when I create a new model instance, but so far I'm getting erratic results: It is rendering different sections of JSON than I indicate, or simply rendering all of it. Any pointers on how to select a specific 'screen' (via its ID) would be greatly appreciated.
Here's an indicative JSON sample code:
[{
"id": 0,
"options": [
{ "text": "Tackle player", "next": [ 0, 1 ] },
{ "text": "Dribble the ball", "next": [ 1 ] }
],
"results": [
{ "text": "Tackle successful", "next": [ 0 ] },
{ "text": "You are close enough to shoot", "next": [ 0, 1 ] }
]
},
{
"id": 1,
"options": [
{ "text": "BLAH", "next": [ 0, 1 ] },
{ "text": "BLAH2", "next": [ 1 ] }
],
"results": [
{ "text": "BLAH3", "next": [ 0 ] },
{ "text": "BLAH4", "next": [ 0, 1 ] }
]
}
]
And here's my backbone code:
var app = app || {};
app.Screen = Backbone.Model.extend({
url: '/api',
parse: function(response){
return response;
}
});
var Screens = Backbone.Collection.extend({
model: app.Screen,
url: '/api'
});
app.AppView = Backbone.View.extend({
initialize: function(parameters){
this.listenTo(this.collection, 'add', this.addOne);
},
render: function(){
this.$el.html("test");
this.addAll();
return this;
},
addAll: function(){
this.collection.each(this.addOne, this);
},
addOne: function(model){
var screen_view = new app.ScreenView({
model: model});
screen_view.render();
this.$el.append(screen_view.el);
}
});
app.ScreenView = Backbone.View.extend({
template: _.template(
'<ul id="options">' +
'<% _.each(options, function(info) { %>' +
'<li id="optionA"><%= info.text %></li>' +
'<% }); %>' +
'</ul>'
),
initialize: function(options) {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
$(function() {
var screen = new app.Screen({id:0}); //CURRENTLY BEHAVING VERY STRANGELY - change ID to 1 and you will get id 0 expected responses
app.screenCollection = new Screens([screen]);
app.screenCollection.fetch();
new app.AppView({
collection: app.screenCollection, el: $('.gameWrapper')
}).render();
});
Why not just reference the array index in your parsed JSON data where screens is the array of screens:
var screen = new app.Screen(screens[index]);
The alternative is to use something like JSONPath to access the object based on the id which is a little more complicated.