Invalid Property on Extended FIORI Application - odata

We are implementing an extended My Quotations Fiori application. Basically we added a new field Sales Order to the UI. The field fetches data from the backend so we also extended our OData service. On the first view, we can successfully call the data. But whenever we navigate to the next view via clicking Edit button, we get this error
Property 'SalesOrder' is invalid. Choose "Refresh" to update pricing information.
Anyone has an idea on how to solve this?
Here is our custom code for S3 view controller. We used WEB IDE to create the extension btw. The second function is for the creation of the Sales Order whenever the quotation has no associated SO tied to it.
manageSalesOrderFields: function() {
alert("manageSalesOrderFields");
var salesOrderId = "";
// hide all fields
view.byId("salesOrderLabel").setVisible(false);
view.byId("salesOrderText").setVisible(false);
view.byId("triggerSalesOrderLabel").setVisible(false);
view.byId("triggerSalesOrderButton").setVisible(false);
$.getJSON("/sap/opu/odata/sap/zlord_my_quotation_srv/QuotationHeaderSet('" + quotationId + "')",
function(data) {
alert("enterHere");
salesOrderId = data.d.SalesOrder;
alert(salesOrderId);
if (salesOrderId !== "" ){
view.byId("salesOrderLabel").setVisible(true);
view.byId("salesOrderText").setVisible(true);
}else{
view.byId("triggerSalesOrderLabel").setVisible(true);
view.byId("triggerSalesOrderButton").setVisible(true);
view.byId("triggerSalesOrderButton").detachPress(sap.ui.controller("...").createSalesOrder);
view.byId("triggerSalesOrderButton").attachPress(sap.ui.controller("...").createSalesOrder);
}
});
},
createSalesOrder: function () {
var createSalesOrderDialog = new sap.m.Dialog("createSoDialog", {
title: "Create Sales Order",
icon: "sap-icon://sales-order",
content: [
new sap.ui.core.HTML({content:"<p style='margin:0;padding: 16px;'>Do want to create a sales order?</p>"})
],
buttons:[
new sap.m.Button({
text: "Yes",
press : function() {
var oModel = new sap.ui.model.odata.ODataModel('/sap/opu/odata/sap/zlord_my_quotation_srv/');
var oParameter = {
"QuotationID" : quotationId
};
oModel.callFunction('/CreateSalesOrder', 'GET', oParameter, 'null',
function (oData, oResponse) {
var responseMessage = JSON.stringify(oResponse.body);
var responseMessageStart = responseMessage.search('<d:Message>');
var responseMessageEnd = responseMessage.search('</d:Message>');
responseMessage = responseMessage.substring(responseMessageStart + 11, responseMessageEnd);
//show MessageToast
sap.m.MessageToast.show(responseMessage);
view.byId("triggerSalesOrderLabel").setVisible(false);
view.byId("triggerSalesOrderButton").setVisible(false);
console.log(responseMessage);
},
function (oError) {
sap.m.MessageToast.show('Error - see log');
console.log(oError);
}
);
createSalesOrderDialog.close();
createSalesOrderDialog.destroy();
}
}),
new sap.m.Button({
text: "No",
press : function() {
createSalesOrderDialog.close();
createSalesOrderDialog.destroy();
}
})
]
});
createSalesOrderDialog.open();
}
We didn't edit anything on the next view controller (CreateQuotations.view.controller.js) since it is not relevant for us to show the SO number on that view.

The error is because of this line:
salesOrderId = data.d.SalesOrder;
How to fix?
Step 1 : Check results first in network tab for the call:
/sap/opu/odata/sap/zlord_my_quotation_srv/QuotationHeaderSet('quotationIdId');
Sample:
Step 2: Check the results hierarchy . How?
console.log(data); //in success call
Step 3: Then restructure your statement to something like this
salesOrderId = data.d.results[0].SalesOrder;
Hope this helps!

Related

SAPUI5: MERGE instead of POST after DELETE

I'm testing a simple sample CRUD app. Everything works well...until I perform a DELETE (omodel.remove()) operation. If the next operation I do is an Insert (create entry, bind to view and submit changes) the app will perform MERGE (with the data of the deleted record) instead of POST and fail. Everything will work afterwards until I repeat this DELETE-INSERT sequence. If following the deletion, try to update an existing record, everything will work as well. Adding an omodel.refresh() at the beginning didn't work. Any ideas?
Starting with empty recordset, adding first record, model before submit changes
Record added, post performed
Ready to add 2nd record, all good in model, one existing and one new entry
2nd record added, another POST, all well
Ready to delete 1st record, situation right before the model.remove() operation, 2 recs, first one pending deletion
Record deleted, DELETE action triggered as expected
Last step, about to enter another record, see the existing and the pending new entry
BAMMM! Record NOT added, app instead of adding the new entry, performed a MERGE with the data of the deleted record!
Code for creating the new entry and passing it to the object page
onActionAdd: function() {
var oModel = this.getView().getModel();
var oParamModel = this.getView().getModel("Params");
oParamModel.setProperty("/ObjectMode", "Add");
oModel.refresh();
//var oNewObject = "{\"Curr\": \"GBP\"}";
var oNewObject = "{\"Pernr\": \"1023912\",\"Begda\":\"" + new Date('2021', '05', '01').toString()
+ "\",\"Endda\":\"" + new Date('2021', '06', '01').toString()
//+ "\",\"ActionDate\":\"" + new Date('2021', '07', '01').toString()
+ "\"}";
oNewObject = JSON.parse(oNewObject);
var oEntry = oModel.createEntry("/Industrial_ActionSet", {
properties: oNewObject
});
oParamModel.setProperty("/EntryId", oEntry.sPath.toString());
this.getRouter().navTo("object", {
objectId: oNewObject.Pernr,
dateFromId: oNewObject.Begda,
dateToId: oNewObject.Endda
});
}
Code for save (insert/update)
onActionSave: function() {
var oModel = this.getView().getModel();
var oParamModel = this.getView().getModel("Params");
var objectMode = oParamModel.getProperty("/ObjectMode");
var self = this;
// abort if the model has not been changed
if (!oModel.hasPendingChanges()) {
MessageBox.information(
this.getResourceBundle().getText("noChangesMessage"), {
id: "noChangesInfoMessageBox",
styleClass: self.getOwnerComponent().getContentDensityClass()
}
);
return;
}
if (objectMode === "Add") {
var sDateFrom = new Date(this.getView().byId("idDateFrom").getDateValue());
var sObjectPath = oParamModel.getProperty("/EntryId") + "/Begda";
oModel.setProperty(sObjectPath, sDateFrom);
var sDateTo = new Date(this.getView().byId("idDateTo").getDateValue());
sObjectPath = oParamModel.getProperty("/EntryId") + "/Endda";
oModel.setProperty(sObjectPath, sDateTo);
var sActionDate = new Date(this.getView().byId("idActionDate").getDateValue());
sObjectPath = oParamModel.getProperty("/EntryId") + "/ActionDate";
oModel.setProperty(sObjectPath, sActionDate);
var sMethod = "POST";
} else {
sMethod = "PUT";
}
oModel.submitChanges({
method: sMethod,
success: function(oData, sResponse) {
MessageToast.show("Record Updated");
self.onNavBack();
},
error: function(oError) {
jQuery.sap.log.error("Action Save oData Failure", oError);
}
});
},
Code for delete
onActionDelete: function() {
var oModel = this.getView().getModel();
var msgText = this.getModel("i18n").getResourceBundle().getText("confirmDelete");
var sPath = this.getView().getBindingContext().sPath;
var self = this;
// Opens the confirmation dialog
MessageBox.confirm(msgText, {
title: "Exit Confirmation",
initialFocus: sap.m.MessageBox.Action.CANCEL,
onClose: function(sButton) {
if (sButton === MessageBox.Action.OK) {
oModel.remove(sPath, {
method: "DELETE",
success: function(data) {
MessageToast.show("Record Deleted");
self.onNavBack();
},
error: function(e) {
jQuery.sap.log.error("Delete Action oData Failure", e);
}
});
} else if (sButton === MessageBox.Action.CANCEL) {
MessageToast.show("Deletion aborted");
return;
}
}
});
},
Thanks, cheers!
This is not the most elaborate way to solve this but problem is related with dates as keys. There are 3 date fields in the entity, 2 of them keys. As soon as I converted the entity date keys to string (still DATS on the backend) everything started working fine...

SAPUI5 oData.V2 How to invoke a function after everything in a batch request is done?

I have an issue while making an SAPUI5 odata V2 batch request :
var that = this;
var oServiceModel = that.getModel("oServiceModel");
odataMod = this.getModel("Service");
odataMod.setUseBatch(true);
var aData = oServiceModel.getData();
var stupidService = _.filter(aData, function (ae) {
return ae.Info === "-N/A";
});
var i = 0 ;
_.forEach(stupidService, function (sap) {
oGlobalBusyDialog.setText("Deleting service :" + sap.ObjectID);
oGlobalBusyDialog.setTitle("Deleting Service");
oGlobalBusyDialog.open();
that.removeService(sap).then(function () {
if (i === 615) {
oGlobalBusyDialog.close();
}
}).catch(function () {});
});
my Delete function is like this:
removeService: function (service) {
var that = this;
return new Promise(
function (resolve, reject) {
odataMod.remove('/ProjectTaskServiceCollection(\'' + service.ObjectID + '\')/', {
success: function (oData) {
resolve(oData);
},
error: function (oResult) {
that.handleError(oResult);
oGlobalBusyDialog.close();
reject(oResult);
}
});
});
What's happening ,is that if I'm trying to delete 500 entry, and if 200 entry cannot be deleted, the error message gets displayed 200 times
How to make it in a way to only display the error message once ?
Also, I want to turn off the batch request once everything is done odataMod.setUseBatch(false); how to do it ?
*EDIT: *
I've manage to do :
var aDeffGroup = odataMod.getDeferredGroups();
//add your deffered group
aDeffGroup.push("deletionGroup");
for (var s = 0; s < 5; s++) {
odataMod.remove('/ProjectTaskServiceCollection(\'' + stupidService[s].ObjectID + '\')/', {
//pass groupid to remove method.
groupId: "deletionGroup"
});
}
odataMod.submitChanges({
// your deffered group id
groupId: "deletionGroup",
success: function() {
//Get message model data from Core and it contains all errors
// Use this data to show in dialog or in a popover or set this to your local model see below code
var aErrorData = sap.ui.getCore().getMessageManager().getMessageModel();
console.log(aErrorData);
}
});
yet stills my console.log(aErrorData); still prints multiple error message
Instead of doing individual deletion odata calls. Add these all remove methods in a single group, then call odatamod.submitChanges() method.
Example:
//get all deffered groups
var aDeffGroup = odataMod.getDeferredGroups();
//add your deffered group
aDeffGroup.push("deletionGroup");
//set it back again to odatamodel
odataMod.setDeferredGroups(aDeffGroup);
odataMod.remove('/ProjectTaskServiceCollection(\'' + service.ObjectID + '\')/', {
//pass groupid to remove method.
groupId: "deletionGroup"});
odataMod.submitChanges({
// your deffered group id
groupId:"deletionGroup",
success: function() {
//Get message model data from Core and it contains all errors
// Use this data to show in dialog or in a popover or set this to your local model see below code
var aErrorData = sap.ui.getCore().getMessageManager().getMessageModel();
});

openlayers 3 featureKey exists in featureChangeKeys

I have an ol.interaction.Select acting on an ol.source.Vector which is within an ol.layer.Vector. I can select and unselect individual countries fine. I am using a dragbox to select multiple countries. If I select anywhere outside of the multiply selected countries, the currently selected get unselected. Excellent!
However, the problem is that if I select a currently selected country within the multiple, I get the AssertionError: Assertion failed: featureKey exists in featureChangeKeys
Here's my Vector layer:
_countrySelectSource = new ol.source.Vector({
url: 'vendor/openlayers/geojson/countries.json',
format: new ol.format.GeoJSON()
});
var countryLayer = new ol.layer.Vector({
title: 'Country Select',
visible: true,
type: 'interactive-layers',
source: _countrySelectSource
});
I add countryLayer to my map, _map.
I then create a _CountrySelect object that allows me to setActive(true|false) on the interactions related to my country selection.
_CountrySelect = {
init : function(){
this.select = new ol.interaction.Select();
_map.addInteraction(this.select);
this.dragbox = new ol.interaction.DragBox({
condition: ol.events.condition.platformModifierKeyOnly
});
_map.addInteraction(this.dragbox);
this.setEvents();
},
setEvents: function(){
var selectedFeatures = this.select.getFeatures();
var infoBox = document.getElementById('info');
var selfDragbox = this.dragbox;
selfDragbox.on('boxend', function() {
// features that intersect the box are added to the collection of
// selected features, and their names are displayed in the "info"
// div
var extent = selfDragbox.getGeometry().getExtent();
_countrySelectSource.forEachFeatureIntersectingExtent(extent, function(feature) {
selectedFeatures.push(feature);
_countryCodes.push(feature.getId());
});
infoBox.innerHTML = _countryCodes.join(', ');
});
// clear selection when drawing a new box and when clicking on the map
selfDragbox.on('boxstart', function() {
selectedFeatures.clear();
infoBox.innerHTML = ' ';
});
_map.on('singleclick', function(event) {
selectedFeatures.clear();
_countryCodes = [];
_map.forEachFeatureAtPixel(event.pixel,function(feature){
selectedFeatures.push(feature);
var id = feature.getId();
var index = _countryCodes.indexOf(id);
if ( index === -1 ) {
_countryCodes.push(feature.getId());
}
});
infoBox.innerHTML = _countryCodes.join(', ');
});
},
setActive: function(active){
this.select.setActive(active);
this.dragbox.setActive(active);
}
};
_CountrySelect.init();
I am not sure if this is an issue with OL3 or my code. Maybe there's an event I'm not handling? Maybe it's the ol.interaction.DragBox (no luck researching on the DragBox). Let me know what further information I can provide.

Sending information to the content script for a context-menu

I've seen many questions regarding context-menu and two-way communication and it appears that I know the answer to my question... "you can't", but I'm going to try anyway.
On each page there is a modal div that is created by a page-mod. This modal is designed to show up when a user hovers over words in text nodes to give a translation of the word. This works perfectly and I don't have any problems with the page-mod.
What I want to do now is allow the user to highlight a selection of text, right click to bring up the context menu where my new menu item will be to "Translate Selection", and then display the selection in the modal div. Here's where the problems begin. I can respond to the context and click events in the content script, which is fine if I didn't have to do a translation. The translation is done by a web service and the content script cannot call a web service because the callbacks don't exist in the context of the content script because it is in a proxy sandbox. That means that all web service calls need to come from main.js (this is how it works in the page-mod). The problem is that the context-menu object in main.js does not have access to the DOM to update the content of the modal div and show it, and it cannot send information to the content script so that the content script can update the DOM and show the modal div. So how do I get the translation to the DOM from the add-on script for the context-menu?
Is what I want to do possible with the SDK, or do I have to undo many hours of work to put my project back into the "old school" way of doing things so I can get the context menu to work correctly?
This is what I have (the page-mod works, need help with the context-menu):
exports.main = function (options, callbacks) {
'use strict';
var myAppMenuItem,
myAppContextMenu,
myAppPanel,
myAppMod,
self = require('self'),
contextMenu = require('context-menu');
myAppMenuItem = require('menuitems').Menuitem();
if (myAppMenuItem.getAttribute('checked') === 'false') {
return;
}
myAppMod = require('page-mod');
myAppMod.PageMod({
include: '*',
contentScriptWhen: 'ready',
contentScriptFile: [self.data.url('jquery-1.7.2.min.js'), self.data.url('myAppmod.js')],
contentStyleFile: self.data.url('myAppmod.css'),
onAttach: function (worker) {
worker.port.on(
'translate',
function (data) {
require('request')
.Request({
url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
content: {
appid : 'myappid',
to : data.to,
from : data.from,
text : data.text
},
onComplete: function (response) {
worker.port.emit('translation', { response : response.text, elementId : data.elementId });
}
})
.get();
}
);
}
});
myAppContextMenu = contextMenu.Item({
label: "Translate Selection",
context: contextMenu.SelectionContext(),
contentScriptFile : [self.data.url('jquery-1.7.2.min.js'), self.data.url('myAppcontextmenu.js')],
onMessage: function (data) {
require('request')
.Request({
url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
content: {
appid : 'myappid',
to : data.to,
from : data.from,
text : data.text
},
onComplete: function (response) {
<what can I do here to send the information to the content script?>
}
})
.get();
}
});
};
Thank you to Wladimir! The following code does what I want it to:
In the main.js for the context-menu:
myAppContextMenu = contextMenu.Item({
label: "Translate Selection",
context: contextMenu.SelectionContext(),
contentScriptFile : [self.data.url('jquery-1.7.2.min.js'), self.data.url('myAppcontextmenu.js')],
onMessage: function (data) {
var text = require('selection').text;
require('request')
.Request({
url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
content: {
appid : 'myappid',
to : data.to,
from : data.from,
text : text
},
onComplete: function (response) {
var index,
tabs = require('sdk/tabs');
for (index = 0; index < workers.length; index += 1) {
if (workers[index].tab === tabs.activeTab) {
workers[index].port.emit('selectionTranslation', { text: text, response : response.text, leftOffset : data.leftOffset, topOffset : data.topOffset });
}
}
}
})
.get();
}
});
and in the content script:
self.on(
'click',
function (node, data) {
'use strict';
var selectedElement = $(node),
messageData =
{
to : 'es',
from : 'en',
topOffset : selectedElement.offset().top + (selectedElement.height() / 2),
leftOffset : selectedElement.offset().left + (selectedElement.width() / 2)
};
self.postMessage(messageData);
}
);
There is a global workers array variable defined in the exports.main function that gets populated by the onAttach function of the page mod as so:
workers.push(worker);
worker.on(
'detach',
function () {
var index = workers.indexOf(worker);
if (index >= 0) {
workers.splice(index, 1);
}
}
);

Calling controller method from JQuery calls occurs twice and also returning error?

Hi guys i have posted a similar post before, but that is for another, now i face a strange and odd issue with my Jquery code. Here i was calling a controller method using Jquery but it is calling twice , so that may cause two entries in my db. Here is what i have written in my JQuery
<script type="text/javascript">
$('#btnSubmit').click(function () {
var instructorUrl = '#Url.Action("ApplyToBecomeInstructor", "InstructorApplication")';
var currentUser = '#Model.CurrentUserId';
var user = [];
var educationList = [];
var experience = $('#Experience').val();
var isWilling = $('#WillingToTravel').is(":checked");
$('#editorRows .editorRow').each(function () {
var education = {
UniversityOrCollege: $(this).find('.university').val(),
AreaOfStudy: $(this).find('.area').val(),
Degree: $(this).find('.degree').val(),
YearReceived: $(this).find('.year').val()
}
educationList.push(education);
});
var applicationFromView = {
EducationalBackgrounds: educationList,
CurrentUserId: currentUser,
Experience: experience,
WillingToTravel: isWilling
}
$.ajax({
type: 'POST',
url: instructorUrl,
dataType: 'JSON',
async: false,
data: JSON.stringify(applicationFromView),
contentType: 'application/json; charset=utf-8',
success: function (data) {
return false;
},
error: function (data) {
alert(xhr.status);
alert(thrownError);
alert(xhr.responseText);
return false;
}
});
});
</script>
and my controller action looks like this
[HttpPost]
public ActionResult ApplyToBecomeInstructor(InstructorApplicationViewModel applicationFromView)
{
Student thisStudent = this.db.Students.Where(o => o.StudentID == applicationFromView.CurrentUserId).FirstOrDefault();
List<PaulSchool.Models.EducationalBackground> educationList = new List<EducationalBackground>();
foreach (var educate in applicationFromView.EducationalBackgrounds)
{
var education = new Models.EducationalBackground
{
YearReceived = educate.YearReceived,
Degree = educate.Degree,
AreaOfStudy = educate.AreaOfStudy,
UniversityOrCollege = educate.UniversityOrCollege
};
educationList.Add(education);
}
var instructorApplication = new InstructorApplication
{
BasicInfoGatheredFromProfile = thisStudent,
Experience = applicationFromView.Experience,
EducationalBackground = new List<Models.EducationalBackground>(),
WillingToTravel = applicationFromView.WillingToTravel
};
instructorApplication.EducationalBackground.AddRange(educationList);
this.db.InstructorApplication.Add(instructorApplication);
this.db.SaveChanges();
return this.Redirect("Index");
}
Error message showing is JSON Parsing error.. but it is confusing to me.
I really wondered why this is happening, can anybody please take a look and help me?
This is what your code does:
$('#btnSubmit').click(function () { // attach a click handler for the button.
...
...
// Look for elements inside the button...
UniversityOrCollege: $(this).find('.university').val(),
Change from click to submit:
$('#formId').submit(function (e) {
...
// Now "this" is the form - not the button.
// Look for elements inside the <form>
UniversityOrCollege: $(this).find('.university').val(),
// Prevent the default form submition
return false // Or: e.preventDefault();
Another tip: use jQuery serialize function.
$('#btnSubmit').click() will fire every time the button is pressed. Often users double click buttons even though it only needs a single click or if you don't give any indication that something is happening they get impatient and click it again. You need some way to determine if the request has been made. There's ways to do this client and server side. The easiest client side way is to disable the button to prevent multiple clicks:
$('#btnSubmit').click(function () {
// Disable the button so it can't be clicked twice accidentally
$('#btnSubmit').attr('disabled', 'disabled');
//...
$.ajax({
//...
complete: function() {
// Make sure we re-enable the button on success or failure so it can be used again
$('#btnSubmit').removeAttr('disabled');
}
});
});

Resources