I'm having issues with saving multiple rows to the back-end. I don't know how to send all the rows in batch, so I was trying to send each row at a time but it hits after it has put the last row into the oEntry.
submitButtonPress: function() {
var oModel = this.getModel();
var hasChanges = oModel.hasPendingChanges();
if (hasChanges) {
var mcJson = {};
//get only rows with changes
var modelChanges = oModel.getPendingChanges();
mcJson = modelChanges;
var mcJsonLength = Object.keys(mcJson).length;
var mcJsonKey = Object.keys(mcJson);
var officeCode = this.byId("officeCombo").getValue();
var oEntry = {};
//for each row get data
for (var i = 0; i < mcJsonLength; i++) {
var item = mcJsonKey[i];
var obj = modelChanges[item];
var estDate = this.convertDate(obj.ESTIMATE_DATE);
oEntry.MRU_ID = obj.EST_MRU_ID.toString();
oEntry.ESTIMATE_PRCT = obj.ESTIMATE_PRCT;
oEntry.INSTALL_READ = obj.INSTALL_READ;
oEntry.PLAN_ESTIMATE = obj.EST_INSTALL;
oEntry.MRU_DATE = estDate;
oEntry.OFFICE_CODE = officeCode.toString();*/
oModel.create("/MRU_ESTSet", oEntry, {
success: function(oData, response) {
sap.m.MessageBox.alert("MRU: " + oEntry.MRU_ID + " EST DATE:" + oEntry.MRU_DATE + " SAVED!");},
error: function(oError) {
sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
} else {
sap.m.MessageBox.alert("No Changes To Submit");
}
}
If you are using oDataModel V2 then what you could just simply do is:
oModel.submitChanges()
This would send all changes made to the model in a batch.
submitChanges method documentation
This is what ended up working for me.
Adding:
oModel.setUseBatch(true);
oModel.create("/MRU_ESTSet", oEntry, {
method: "POST",
success: function(oData) {
//sap.m.MessageBox.alert("success sent!");
},
error: function(oError) {
//sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
oModel.submitChanges({
success: function(oData, response) {
sap.m.MessageBox.success("Success Saving Entries!");
},
error: function(oError) {
sap.m.MessageBox.error("Error Saving Entries!!");
}
});
So the function ends up like this and only sends one confirmation instead of many:
submitButtonPress: function() {
var oModel = this.getModel();
oModel.setUseBatch(true);
var hasChanges = oModel.hasPendingChanges();
if (hasChanges) {
var mcJson = {};
var modelChanges = oModel.getPendingChanges();
mcJson = modelChanges;
var mcJsonLength = Object.keys(mcJson).length;
var mcJsonKey = Object.keys(mcJson);
var officeCode = this.byId("officeCombo").getValue();
for (var i = 0; i < mcJsonLength; i++) {
var item = mcJsonKey[i];
var obj = modelChanges[item];
var estDate = this.convertDate(obj.ESTIMATE_DATE);
var oEntry = {
MRU_ID: obj.EST_MRU_ID,
ESTIMATE_PRCT: obj.ESTIMATE_PRCT,
INSTALL_READ: obj.INSTALL_READ,
PLAN_ESTIMATE: obj.EST_INSTALL,
MRU_DATE: estDate,
OFFICE_CODE: officeCode
};
oModel.create("/MRU_ESTSet", oEntry, {
method: "POST",
success: function(oData) {
//sap.m.MessageBox.alert("success sent!");
},
error: function(oError) {
//sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
oModel.submitChanges({
success: function(oData, response) {
sap.m.MessageBox.success("Success Saving Entries!");
},
error: function(oError) {
sap.m.MessageBox.error("Error Saving Entries!!");
}
});
} else {
sap.m.MessageBox.alert("No Changes To Submit");
}
},
Related
In Google Apps Script, I'm using some code I adapted from a project I found. It calls an API endpoint and lays out the data in a spreadsheet. I was able to get it to loop through multiple API calls in order to pull data from multiple documents. However, the code breaks if it finds a document with no data. In this case, I want it to just skip that iteration and start again at the next cardIds.forEach iteration.
Here's a link to a sample sheet.
I tried:
if (response == "") {
return;
}
But no dice. Here's the full code (also it's very inefficient. I have params on their twice because I'm not sure how to consolidate them with all the functions inside other functions..)
const DATA_SHEET = "Data";
const USERNAME_CELL = "B1";
const API_TOKEN_CELL = "B2";
const CARD_ID_COL = "Cards!B:B"
const DATA_RANGE = "A4:C"
var getNextPage = function(response) {
var url = response.getAllHeaders().Link;
if (!url) {
return "";
}
return /<([^>]+)/.exec(url)[1];
};
var getIt = function(path, username, apiToken) {
var params = {
"method": "GET",
"muteHttpExceptions": true,
"headers": {
"Content-Type": "application/json",
"Authorization": "Basic " + Utilities.base64Encode(username + ":" + apiToken),
"x-guru-application": "spreadsheet",
"X-Amzn-Trace-Id": "GApp=spreadsheet"
}
};
var response = UrlFetchApp.fetch(path, params);
var data = JSON.parse(response.getContentText());
// check if there's another page of results.
var nextPage = getNextPage(response);
if (nextPage) {
data.nextPage = nextPage;
};
return data;
};
var getItAll = function(url, username, apiToken, callback) {
var data = [];
while (url) {
var page = getIt(url, username, apiToken);
var startIndex = data.length;
page.forEach(function(a) {
data.push(a);
});
// get the url of the next page of results.
url = page.nextPage;
if (callback) {
// the second parameter is whether we're done or not.
// if there's a url for the next page that means we're not done yet.
callback(data, startIndex, page.length, url ? false : true);
}
}
return data;
};
function eachCard() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(DATA_SHEET);
sheet.getRange(DATA_RANGE).clearContent();
var username = sheet.getRange(USERNAME_CELL).getValue();
var apiToken = sheet.getRange(API_TOKEN_CELL).getValue();
var cardIds = sheet.getRange(CARD_ID_COL).getValues().flat().filter(r=>r!="");
var params = {
"method": "GET",
"muteHttpExceptions": true,
"headers": {
"Content-Type": "application/json",
"Authorization": "Basic " + Utilities.base64Encode(username + ":" + apiToken),
"x-guru-application": "spreadsheet",
"X-Amzn-Trace-Id": "GApp=spreadsheet"
}
};
cardIds.forEach(function (cardId) {
var fullUrl = "https://api.getguru.com/api/v1/cards/"+cardId+"/comments"
var cardComments = getItAll(fullUrl, username, apiToken);
var fullUrl = "https://api.getguru.com/api/v1/cards/"+cardId+"/extended"
var response = UrlFetchApp.fetch(fullUrl, params);
var cardData = JSON.parse(response.getContentText());
var sheetLastRow = sheet.getLastRow();
var range = sheet.getRange("A" + sheetLastRow);
if (range.getValue() !== "") {
var lastRow = sheetLastRow+1;
} else {
var lastRow = range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow()+1;
}
cardComments.forEach(function(comment, commentIndex) {
sheet.getRange(lastRow + commentIndex, 1).setValue(comment.dateCreated);
sheet.getRange(lastRow + commentIndex, 1 + 1).setValue(comment.content);
sheet.getRange(lastRow + commentIndex, 1 + 2).setValue(cardData.preferredPhrase);
});
});
}
I need to fetch data from multiple API and display them in the table.
What I came up with is:
var req = $.ajax({
url: "....linkhere",
dataType: 'jsonp'
});
var req = $.ajax({
url: "....linkhere1",
dataType: 'jsonp'
});
req.done(function(data) {
console.log(data);
var infoTable = $("<table />");
var arrayL = data.length;
var outputString = '';
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
});
Although, this way I can only get data from one api. How can I take it from multiple?
EDIT:
I am trying to add text input, so I can send request about specific word. I am trying to append existing table with new results. I was trying to alter code which was provided as an answer below. However, I did something work, and it does not work.
$("#inputChoice").on("blur", function() {
let choice = $(this).val();
let req = $.ajax({
url: "...APIlink"+choice,
dataType: "jsonp"
});
req.done(function (data) {
console.log(data);
var infoTable = $("<table />");
let arrayL = data.length;
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
titleCell.addClass("title-row");
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
detailCell.addClass("details-row")
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
});
Request data from endpoints and when they're all done create a table
function multiReq(...links) {
let responseCount = links.length;
const responses = [];
let handler;
function responseHandler(i) {
return data => {
responseCount -= 1;
responseCount === 0
? handler([].concat(...responses))
: (responses[i] = data)
}
}
links.forEach((link, i) => $.ajax({
url: link,
dataType: 'jsonp'
}).done(responseHandler(i)));
return {
done(callback) {
handler = callback;
}
};
}
multiReq(link1, link2).done((data) => {})
or
function multiReq(...links) {
return Promise.all(links.map(link => $.ajax({
url: link,
dataType: 'jsonp'
}))).then((...responses) => [].concat(...responses))
}
multiReq(link1, link2).then(data => {
// create table
})
or
function multiReq(...links) {
return $.when(...links.map(link => $.ajax({
url: link,
dataType: 'jsonp'
}))).then((...responses) => [].concat(...responses.map(([data]) => data)))
}
multiReq(link1, link2).done(data => {
// create table
})
or as close to your code as possible:
var req1 = $.ajax({
url: "https://wt-65edf5a8bfb22e61214c31665c92dbd2-0.sandbox.auth0-extend.com/link-1",
//dataType: 'jsonp'
});
var req2 = $.ajax({
url: "https://wt-65edf5a8bfb22e61214c31665c92dbd2-0.sandbox.auth0-extend.com/link-1",
//dataType: 'jsonp'
});
$.when(req1, req2).done(function([data1], [data2]) {
var data = data1.concat(data2); // merge data from both request into one
//console.log(data);
var infoTable = $("<table />");
var arrayL = data.length;
var outputString = '';
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="display-resources"></div>
this is my scenario. As I am new to Microsoft Dynamics coding, need a solution for my code.
I have two entities named Acc and Con, where Acc is parent and Con is child entity of Acc.
I have created a lookup field of Acc in Con entity along with fields with similar datatype in the two entities.
So, whenever a change in parent record is made in the fields and saved, the changes should be done automatically in the corresponding fields of the child record.
The part I get the error is to update but am able to retrieve the code. So the record fails to update.
The error I get now is
ReferenceError: FetchRecordsCallBack is not defined at Object.GetRecs.jQuery.ajax.success
Your answers and suggestions are requested and welcome. :) Here below is my code.
function accupdate() {
debugger;
var PrvdLocData;
var name;
var age;
var sex;
var address;
var phonenumber;
var degree;
var sslcpercentage;
var hscpercentage;
var ugpercentage;
var PrvdLocData = new Array();
var EmpId = Xrm.Page.data.entity.getId();
//parent fields
if (Xrm.Page.getAttribute("new_name").getValue() != null) {
name = Xrm.Page.getAttribute("new_name").getValue();
}
if (Xrm.Page.getAttribute("new_age").getValue() != null) {
age = Xrm.Page.getAttribute("new_age").getValue();
}
if (Xrm.Page.getAttribute("new_sex").getValue() != null) {
sex = Xrm.Page.getAttribute("new_sex").getValue();
}
if (Xrm.Page.getAttribute("new_address").getValue() != null) {
address = Xrm.Page.getAttribute("new_address").getValue();
}
if (Xrm.Page.getAttribute("new_phonenumber").getValue() != null) {
phonenumber = Xrm.Page.getAttribute("new_phonenumber").getValue();
}
if (Xrm.Page.getAttribute("new_degree").getValue() != null) {
degree = Xrm.Page.getAttribute("new_degree").getValue();
}
if (Xrm.Page.getAttribute("new_sslcpercentage").getValue() != null) {
sslcpercentage = Xrm.Page.getAttribute("new_sslcpercentage").getValue();
}
if (Xrm.Page.getAttribute("new_hscpercentage").getValue() != null) {
hscpercentage = Xrm.Page.getAttribute("new_hscpercentage").getValue();
}
if (Xrm.Page.getAttribute("new_ugpercentage").getValue() != null) {
ugpercentage = Xrm.Page.getAttribute("new_ugpercentage").getValue();
}
var context = Xrm.Page.context;
var serverurl = context.getClientUrl();
var ODatapath = serverurl + "/XRMServices/2011/OrganizationData.svc";
var retrieveResult = new XMLHttpRequest();
var dtqeurl = ODatapath + "/new_conSet?$select=new_name,new_YourAge,new_YourSex,new_HomeAddress,new_Contact,new_DegreeType,new_SSLCPercent,new_HSCPercent,new_conId,new_UGPercent&$filter=new_AccName/Id eq guid'" + EmpId + "'";
GetRecs("PrvtLoc", dtqeurl);
function GetRecs(entity, url) {
jQuery.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: url,
async: false,
beforeSend: function XMLHttpRequest(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null && data.d.results != null) {
AddRecordsToArray(data.d.results, entity);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
// alert("Error : has occured during retrieval of the records ");
}
});
}
function AddRecordsToArray(result, entity) {
$.each(result, function () {
if (entity == "PrvtLoc")
PrvdLocData.push(this);
});
}
if (PrvdLocData.length > 0) {
for (i = 0; i < PrvdLocData.length; i++) {
//Object Assigning
var crmobject = new Object();
//Variable declaration for Child entity's primarykey (ID)
var childId = PrvdLocData[i].new_conId;
//Setting child entitiy's value with parent entity's variable
crmobject.new_name = name;
crmobject.new_YourAge = parseInt(age);
crmobject.new_YourSex = sex;
crmobject.new_HomeAddress = toString(address);
crmobject.new_Contact = parseInt(phonenumber);
crmobject.new_DegreeType = degree;
crmobject.new_SSLCPercent = sslcpercentage;
crmobject.new_HSCPercent = hscpercentage;
crmobject.new_UGPercent = ugpercentage;
// update starts...
var serverUrl = Xrm.Page.context.getClientUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var crmobject = new Object();
// Specify the ODATA entity collection
var ODATA_EntityCollection = "/new_conSet";
var jsonEntity = window.JSON.stringify(crmobject);
//Asynchronous AJAX function to Create a CRM record using OData
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + "(guid'" + childId + "')",
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("updated");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("fail to update");
}
});
}
}
}
crmobject.new_name = name;
crmobject.new_YourAge = parseInt(age);
crmobject.new_YourSex = { Value: sex };
crmobject.new_HomeAddress = address;
crmobject.new_Contact = parseInt(phonenumber);
crmobject.new_DegreeType = { Value: degree };
crmobject.new_SSLCPercent = parseFloat(sslcpercentage).toFixed(2);
crmobject.new_HSCPercent = parseFloat(hscpercentage).toFixed(2);
crmobject.new_UGPercent = parseFloat(ugpercentage).toFixed(2);
A bit new to JS. I'm using Parse.com's CloudCode in order to calculate the "score" of a "Post" instance. I retrieve any "Votes" associated with a post, and then sum up their "value", then return that value.
Parse.Cloud.define("postScore", function(request, response) {
var postId = request.params.postId;
var post = Parse.Object.extend("Post");
post.id = postId;
var query = new Parse.Query("Vote");
query.equalTo("post", post);
query.find({
success: function(results) {
var sum = 0;
for (var i = 0; i < results.length; ++i) {
sum += results[i].get("value");
}
response.success(sum);
},
error: function() {
response.error("Could not calculate value");
}
});
});
Getting this error:
2014-05-02 19:21:09.124 XXX[33361:2d3b] Error: undefined (Code: 141,
Version: 1.2.19)
Not too sure what the issue is.
Calling it in my iOS app like so:
- (void)fetchPostScores
{
for (BVYPost *post in _postsArray) {
[PFCloud callFunctionInBackground:#"postScore" withParameters:#{#"postId": post.objectId} block:^(NSNumber *score, NSError *error) {
if (!error) {
post.score = score;
}
}];
}
}
This is wrong:
var post = Parse.Object.extend("Post");
post.id = postId;
The correct syntax would be:
var post = new Parse.Object("Post");
post.id = postId;
that is my ajax call:
function getEle(id) {
var element = new Array();
$.ajax({
async: false,
url: "map.php",
type: "POST",
dataType: 'json',
data: {
"id": id
},
success: function (data) {
var resultArr = new Array();
var resultArr = data;
var state = new Array();
for (var s = 0; s < resultArr.length; s++) {
state[s] = resultArr[s];
element[s] = id;
element[s] = state[s];
}
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
return element;
}
Have some solution kindly post it..... thanks in advance....
you can use window.location in javascript.
success: function (data) {
var resultArr = new Array();
var resultArr = data;
var state = new Array();
for (var s = 0; s < resultArr.length; s++) {
state[s] = resultArr[s];
element[s] = id;
element[s] = state[s];
}
window.location = "yourpage address";// add this line
}