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;
}
};
Related
I've created a kendo grid, and need to insert kendo drop down into one of the columns. I need to get the data for the drop down from another data source. It kind of works, however, the problem is when I have chosen a value from the drop down and the drop down closes, instead of displaying that value it goes into editable mode. Only when I click outside of the dropdown, it displays the correct value. Here is a gif of the issue:
https://media2.giphy.com/media/KyMGB7FmFQMVTChFA7/giphy.gif
How could this issue be solved?
I have successfully created a kendo grid with a drop down list already. The only difference seems to be that there only one data source is used, but here two are used. Here is some of the code for the drop down:
title: "Type",
field: "productType.name", //this property is from the data source used for grid
template: "<kendo-drop-down-list k-value=\"dataItem.productType.id\"
k-options=\"productTypeOptions\" ng-change=\"productTypeChanged(dataItem, 'productType')\"
ng-model=\"dataItem.productType.id\"></kendo-drop-down-list>"
}...];
$scope.productTypes = {
data: [{ name: "Value 1", id: "1" }, { name: "Value 2", id: "2" }]
}
$scope.productTypeDataSource = new kendo.data.DataSource({
schema: {
data: "data",
model: {
fields: {
id: { type: "number" },
name: { type: "string" }
}
}
},
data: $scope.productTypes,
serverPaging: true,
serverSorting: true,
serverFiltering: true
});
$scope.productTypeOptions = {
dataSource: $scope.productTypeDataSource,
dataTextField: "name",
dataValueField: "id"
};
$scope.productTChanged = function (dataItem, field, productArray, dataSource) {
var index = dataSource.indexOf(dataItem);
var c = productArray.data[index];
if (c == null) return;
c[field] = dataItem[field];
return c;
};
$scope.productTypeChanged = function (dataItem, field) {
$scope.productTChanged(dataItem, field, $scope.products, $scope.productDataSource);
};```
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 new in sharepoint. I am using Sharepoint 2013.
I want to retrieve name and email id in People Or Group column using REST API.
My list contains two such columns. Please help me to retrieve title and email ids of both the columns
How to retrieve user field value using SharePoint REST
Using $expand OData operator you can specify that the request returns projected fields from User Information List list for user field.
ListItem resource endpoint: https://[site]/_api/web/lists/getbytitle('<list title>')/items(<item id>)?$select=<user field name>/Name,<user field name>/EMail&$expand=<user field name>
Examples
Assume a Tasks List that contains AssignedTo (multi-valued) and Author (single-valued) user fields.
The first example demonstrates how to retrieve AssignedTo column user details:
/_api/web/lists/getbytitle('Tasks')/items(1)?$select=AssignedTo/Name,AssignedTo/EMail&$expand=AssignedTo
returns Name and Title for AssigntedTo column:
{
"d": {
"__metadata": {
"id": "764f494a-7186-4b83-9db0-2bcf1a0930a5",
"uri": "https://contoso.sharepoint.com/_api/Web/Lists(guid'71284427-d86e-424f-ae07-2e0c53b9ac4a')/Items(1)",
"etag": "\"3\"",
"type": "SP.Data.TasksListItem"
},
"AssignedTo": {
"results": [
{
"__metadata": {
"id": "a06b28ff-9356-4aa9-8f38-f75107058fd2",
"type": "SP.Data.UserInfoItem"
},
"Name": "i:0#.f|membership|username#contoso.onmicrosoft.com",
"EMail": "username#contoso.onmicrosoft.com"
}
]
}
}
}
The following example demonstrates how to retrieve Author and AssignedTo user field user values:
Endpoint Url: /_api/web/lists/getbytitle('Tasks')/items(1)?$select=Author/Name,Author/EMail,AssignedTo/Name,AssignedTo/EMail&$expand=AssignedTo,Author
Result:
{
"d": {
"__metadata": {
"id": "e29690e4-3813-44ce-a828-160ad072666d",
"uri": "https://contoso.sharepoint.com/_api/Web/Lists(guid'71284427-d86e-424f-ae07-2e0c53b9ac4a')/Items(1)",
"etag": "\"3\"",
"type": "SP.Data.TasksListItem"
},
"Author": {
"__metadata": {
"id": "6dc8fe57-1865-464f-aaa3-f7b8bb555f20",
"type": "SP.Data.UserInfoItem"
},
"Name": "i:0#.f|membership|username#contoso.onmicrosoft.com",
"EMail": "username#contoso.onmicrosoft.com"
},
"AssignedTo": {
"results": [
{
"__metadata": {
"id": "b9a1d6f8-4bec-4ec8-b940-fdaeac2eff37",
"type": "SP.Data.UserInfoItem"
},
"Name": "i:0#.f|membership|username#contoso.onmicrosoft.com",
"EMail": "username#contoso.onmicrosoft.com"
}
]
}
}
}
JavaScript example
function getItemDetails(webUrl,listTitle,itemId,selectFields, expandFields){
var endpointUrl = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + itemId + ")";
endpointUrl+= '?$select=' + selectFields.join(",");
endpointUrl+= '&$expand=' + expandFields.join(",");
return executeRequest(endpointUrl,'GET');
}
function executeRequest(url,method,headers,payload)
{
if (typeof headers == 'undefined'){
headers = {};
}
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if(method == "POST") {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var selectFields = ['Author/Name','Author/EMail','AssignedTo/Name','AssignedTo/EMail'];
var expandFields = ['Author','AssignedTo'];
getItemDetails(webUrl,'Tasks',2,selectFields,expandFields)
.done(function(data){
//print MULTI-valued user field: AssignedTo
console.log('AssignedTo user field value:')
for(var i = 0; i< data.d.AssignedTo.results.length;i++) {
console.log(data.d.AssignedTo.results[i].EMail);
console.log(data.d.AssignedTo.results[i].Name);
}
//print SINGLE-valued user field: Author
console.log('Author user field value:')
console.log(data.d.Author.EMail);
console.log(data.d.Author.Name);
});
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 have a viewmodel of state in which i have five fields out of five one field is hidden field .Which i want to be get updated whenever i am trigging an ajax request. my servlet respond a value . I want this value be get updated on the basis of ajax response. here is my viewmodel
var dummyData = [{ "nsc": "1", "name": "us", "bic": "united states", "identifier": "us" }, { "nsc": "2", "name": "europe", "bic": "europe", "identifier": "us" }, { "nsc": "3", "name": "aus", "bic": "aus", "identifier": "us" }];
function State(data) {
this.nsc = ko.observable(data.nsc || "");
this.nscto = ko.observable(data.nscto || "");
this.bic = ko.observable(data.bic || "");
this.name = ko.observable(data.name || "");
this.hiddenField = ko.observable(data.identifier || "");
}
function StateViewModel() {
var self = this;
self.States = ko.observableArray([]);
self.PopulateStates = ko.computed(function () {
ko.utils.arrayForEach(dummyData, function (item) {
self.States.push(new State(item));
});
});
self.nsc = ko.observable();
self.nscto = ko.observable();
self.bic = ko.observable();
self.hiddenField = ko.observable();
self.name = ko.observable();
}
Here is my addState function on which i am making an ajax request
self.addState = function (state) {
var stateData = ko.toJSON({ data: new State({ nsc: self.nsc(), nscto: self.nscto(), bic: self.bic(), name: self.name() }) });
$.ajax
({
data: "action=" + "addarea" + "&jsonData=" + stateData,
url: '/bin/stateUpdate/add',
dataType: 'json',
type: 'GET',
success: function (data) {
var identifier = data['identifier'];
alert(identifier); // checking servlet reponse
self.hiddenField(identifier);
self.States.push(new State({
nsc: self.nsc(),
nscto: self.nscto(),
bic: self.bic(),
name: self.name(),
hiddenField: self.hiddenField(identifier)
}));
},
error: function (exception) {
alert("fail");
}
});
/* $.post("/bin/stateUpdate/add", stateData, function(returnedData) {
bank.hiddenField(returnedData);
})*/
};
i want to update hiddenField on the basis of value getting from servlet.and addstate function is inside viewmodel. How can i set this value second when i am trying making ajax request using Knockout method $.post it is not working. can anybody help ?