We are in the process of remediation, re-engineering old JS web resources for latest D365 v9 sdk changes w.r.t Client scripting API improvements & deprecation.
When rewriting the web api methods using Xrm.WebApi, we end up with this blocker.
The scenario is setting null to lookup, and tried the below code:
var data = {
"abc_relatedentity#odata.bind": null
};
Xrm.WebApi.updateRecord("abc_entity", abc_entityid, data).then(successCallback, errorCallback);
This is throwing error:
"The 'odata.bind' instance or property annotation has a null value. In OData, the 'odata.bind' instance or property annotation must have a non-null string value."
The idea is to retire the below redundant XHR request code. But this is the only workaround we have now (referring MSDN).
var req = new XMLHttpRequest();
req.open("DELETE", Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.0/accounts(recordGUID)/account_parent_account/$ref", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 204 || this.status === 1223) {
//Success - No Return Data - Do Something
}
}
};
req.send();
Anybody faced this & handled it? Am I missing something?
You have to use Delete method to remove the lookup value
format is as follows:
/api/data/v8.0/accounts(1DD18913-11CB-E511-80D2-C4346BDC11C1)/primarycontactid/$ref
I think set the column to null is enough, please make sure you removed '#odata.bind'
var data = {
"abc_relatedentity": null
};
This is working for me.
you should try Xrm.WebApi.online.execute or Xrm.WebApi.online.executeMultiple
var Sdk = window.Sdk || {};
/**
* Request to execute an update operation
*/
Sdk.UpdateRequest = function(entityName, entityId, payload) {
this.etn = entityName;
this.id = entityId;
this.payload = payload;
};
// NOTE: The getMetadata property should be attached to the function prototype instead of the
// function object itself.
Sdk.UpdateRequest.prototype.getMetadata = function () {
return {
boundParameter: null,
parameterTypes: {},
operationType: 2, // This is a CRUD operation. Use '0' for actions and '1' for functions
operationName: "Update",
};
};
// Construct a request object from the metadata
var payload = {
"_abc_relatedentity_value": null
};
var updateRequest = new Sdk.UpdateRequest("abc_entity", abc_entityid, payload);
// Use the request object to execute the function
Xrm.WebApi.online.execute(updateRequest).then(
function (response) {
console.log(response)
},
function(error) {
console.log(error.message);
// handle error conditions
}
);
Great news! You can set lookup field to null in PATCH request by adding this header to your request.
autodisassociate: true
And then you can use something like this to alter your lookup field in any way:
SetLookupField(requestBody, "systemusers", "msdfm_MyUser", null)
// Or
SetLookupField(requestBody, "systemusers", "msdfm_MyUser", "f5b0b514-aea8-ea11-a812-000d3a569fe1")
// ...
private static void SetLookupField(JObject requestBody, string typePlural, string name, string value)
{
if (!string.IsNullOrEmpty(value))
{
requestBody.Add($"{name}#odata.bind", $"/{typePlural}({value})");
}
else
{
requestBody.Add($"_{name.ToLower()}_value", null);
}
}
OP uses XMLHttpRequest anyway, so I thought, a way to do this using PATCH will be relevant here.
To set null on the lookup use:
var data = { _[LookupFieldName]_value : null }
Xrm.WebApi.updateRecord("abc_entity", abc_entityid, data).then(successCallback, errorCallback
For example to remove contact.parentcustomerid field value you need to use:
var data = {};
data._parentcustomerid_value = null
var t = await Xrm.WebApi.updateRecord("contact", "{0200E6F5-1D21-E811-A954-0022480042B3}", data)
I just tried in v9.1.0.3832
var data = { _[LookupFieldName]_value : null } is working for me.
var data =
{
"statecode": 1,
"*_myprefix_mylookupfieldname_value*": null
}
Xrm.WebApi.updateRecord("*entityName*", *recordId*, data);
Related
My Ajax method is calling action method in controller, and succeeding in the call return. However the object I am passing is always null.
I have read many, maybe not all as there are quite a few, similar questions. I have tried different things, such as different variations of removing dataType and contentType from the ajax function. I have set break points in the action and set alerts in scripts to verify the object is not null before sending to the JsonResult Action. I have verified that data from the Action method is reaching the succeeded section of the ajax function.
So Here is the scenario: I have an MVC Core 2.2 index page. I added a search textbox. everything works correctly If I block JS in the browser, So I know the HTML is correct. But I wanted to give an Ajax option for a "more pleasant" user experience. I actually did get the ajax to work on simple hard coded strings. But now for some reason the passed in object is null.
Lets start with the view's script:
//This is the Object I want passed through Ajax
//class pageValues {
// constructor(){
// this.sortColumn = $("#inpSortColumn").val();
// this.sortOrder = $("#inpSortOrder").val();
// this.filter = $("#Filter").val();
// this.message = "";
// this.currentPage = $("#inpCurrentPage").val();
// this.recordsPerPage = $("#inpPageSize").val();
// this.recordCount = 0;
// }
//}
// I also tried as a simple variable without a constructor and added
// default values incase undefined values were causing issues
var pageValues = {
sortColumn: ($("#inpSortColumn").val() == undefined ) ? "LastName" : $("#inpSortColumn").val(),
sortOrder: ($("#inpSortOrder").val() == undefined ) ? "ASC" : $("#inpSortOrder").val(),
filter: ($("#Filter").val() == undefined ) ? "" : $("#Filter").val(),
message: ($("#inpMessage").val() == undefined ) ? "" : $("#inpMessage").val(),
currentPage: ($("#inpCurrentPage").val() == undefined) ? 1: $("#inpCurrentPage").val(),
recordsPerPage: ($("#inpPageSize").val() == undefined) ? 5 : $("#inpPageSize").val(),
totalRecords: ($("#inpTotalRecords").val() == undefined ) ? 0 : $("#inpTotalRecords").val()
};
$(document).ready(function () {
// If we are here, the browser allows JS
// So, replace the submit buttons with Ajax functions
ReplaceHtml();
});
function ReplaceHtml() {
// Search Button
var divSearch = $("#divSearchBtn");
divSearch.hide();
divSearch.empty();
divSearch.append('<button id="btnAjaxSearch" type="button" ' +
'class="" onclick="RequestRecords();">Search</button>');
divSearch.show();
}
// Here we call the Ajax function passing the data object and the callback function
function RequestRecords() {
alert($("#Filter").val()); // This is just to Verify value is present
AjaxCallForRecords(pageValues, ReturnedData);
}
// This is the callback function
function ReturnedData(data) {
// This verifies we hit the callback
alert("inside ajax callback");
// The Verification that the Object returned is valid.
// The problem appeared here,
// The firstname was always the same no matter the Search Filter.
// Telling me the object on the server side receiving the 'pageValues'
// had been recreated due to being null.
alert(data.users[0].firstName);
}
// Of course, here is the ajax function
// I have played around with data and content settings
// When I changed those I got 'Response Errors' but could never get the ResponseText
function AjaxCallForRecords(dataToSend, callback) {
console.log(dataToSend); // This prove Data is here
$.ajax({
type: "GET",
url: '#Url.Action("Index_Ajax","ApplicationUsers")',
data: JSON.stringify(dataToSend),
dataType: "json",
contentType: "application/json",
success: function (data) { callback(data); },
error: function (data) { alert("Error. ResponseText: " + data.responseText); }
});
}
</script>
Ok, Now to the Controller:
public JsonResult Index_Ajax([FromBody] UsersCodeAndClasses.PageValues pageValues)
{
// A break point here reveals 'pageValues' is always null - this is the problem.....
// In the GetFilteredData function I do create a new 'pageValues' object if null
// So my Search 'Filter' will always be empty, and I will always get all the records.
// Get Records
List<InputUser> users = _usersCode.GetFilteredData(pageValues);
// The next block of code assembles the data to return to the view
// Again the 'pageValues' is null because that is what gets passed in, or rather, never assigned
//Build Return Data
UsersCodeAndClasses.AjaxReturnData data = new UsersCodeAndClasses.AjaxReturnData()
{
pageValues = pageValues,
users = users
};
return Json(data);
}
And Finally, The Server side 'pageValues' declaration:
public class PageValues
{
// Class used to pass page and sorting information to Ajax Call
public string sortColumn { get; set; } = "LastName";
public string sortOrder { get; set; } = "ASC";
public string filter { get; set; } = "";
public string message { get; set; } = "";
public int currentPage { get; set; } = 1;
public int recordsPerPage { get; set; } = 5;
public int recordCount { get; set; }
}
public class AjaxReturnData
{
// Class is used to pass multiple data to the Ajax Call
public PageValues pageValues { get; set; }
public List<InputUser> users { get; set; }
}
So, I am expecting data to be passed, I just do not know why the server is not assigning the data. I am new at this and could use an experienced eye.
Thanks
Simply change your type from GET to POST in Ajax call.
I spent some more time researching everything about ajax return values and classes.
Ultimately, my class was malformed, once I changed that it started working. I also changed the type to POST, I did not want to use POST just to read records. But I am sending a lot of data keeping up with search, pagination and sorting.
The below code works though I feel like it is very verbose and some parts may be unnecessary. Hope it helps someone, and please feel free to comment and help me out on things that could help others.
<script>
// Class to use for ajax data
class pageValues {
constructor(){
this.sortColumn = ($("#inpSortColumn").val() == undefined) ? "LastName" : $("#inpSortColumn").val();
this.sortOrder = ($("#inpSortOrder").val() == undefined) ? "ASC" : $("#inpSortOrder").val();
this.filter = ($("#Filter").val() == undefined) ? "" : $("#Filter").val();
this.message = ($("#inpMessage").val() == undefined) ? "" : $("#inpMessage").val();
this.currentPage = ($("#inpCurrentPage").val() == undefined) ? 1 : $("#inpCurrentPage").val();
this.recordsPerPage = ($("#inpPageSize").val() == undefined) ? 5 : $("#inpPageSize").val();
this.totalRecords= ($("#inpTotalRecords").val() == undefined) ? 0 : $("#inpTotalRecords").val();
}
get SortColumn() { return this.sortColumn; }
set SortColumn(value) { this.sortColumn = value; }
get SortOrder() { return this.sortOrder; }
set SortOrder(value) { this.sortOrder = value;}
get Filter() { return this.filter; }
set Filter(value) { this.filter = value; }
get Message() { return this.message; }
set Message(value) { this.message = value; }
get CurrentPage() { return this.currentPage; }
set CurrentPage(value) { this.currentPage = value; }
get RecordsPerPage() { return this.recordsPerPage; }
set RecordsPerPage(value) { this.recordsPerPage = value; }
get TotalRecords() { return this.totalRecords; }
set TotalRecords(value) { this.totalRecords = value; }
}
$(document).ready(function () {
// If we are here, the browser allows JS
// So, replace the submit buttons with Ajax functions
ReplaceHtml();
});
function ReplaceHtml() {
// Search Button
var divSearch = $("#divSearchBtn");
divSearch.hide();
divSearch.empty();
divSearch.append('<button id="btnAjaxSearch" type="button" ' +
'class="" onclick="RequestRecords();">Search</button>');
divSearch.show();
}
// Here we call the Ajax function passing the data object and the callback function
function RequestRecords() {
alert($("#Filter").val()); // This is just to Verify value is present
AjaxCallForRecords(new pageValues(), ReturnedData);
}
// This is the callback funtion
function ReturnedData(data) {
// The verification we hit the callback
alert("inside ajax callback");
alert(data.users[0].firstName);
}
// Ajax function
function AjaxCallForRecords(dataToSend, callback) {
console.log(dataToSend);
$.ajax({
type: "POST",
url: '#Url.Action("Index_Ajax","ApplicationUsers")',
data: JSON.stringify(dataToSend),
dataType: "json",
contentType: "application/json",
success: function (data) { callback(data); },
error: function (data) { alert("Error. ResponseText: " + data.responseText); }
});
}
</script>
I'm trying to get user lang from User class in Parse Cloud. lang is one of the columns in User class. I wanna get lang of the user. My entire Cloud Code is as following (it didn't work):
Parse.Cloud.beforeSave('Order', function(request, response) {
var orderState = request.object.get('orderState');
var subtitleMessage = '';
var userLang = '';
var currentUser = request.object.get('user');
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('objectId', currentUser.id);
.find()
.then((result)=>{
userLang = result.get('lang');
})
if (orderState === undefined || ['nonApproved', 'approved', 'delivered', 'canceled'].indexOf(orderState) < 0) {
response.error("OrderState is null or not one the ['nonApproved', 'approved', 'delivered', 'canceled']!");
} else {
var query = new Parse.Query(Parse.Installation);
query.include('user');
query.equalTo('user', request.object.get('user'));
Parse.Push.send(
{
where: query,
data: {
title: "MyTitle",
alert: subtitleMessage
}
},
{
success: function() {
},
error: function(error) {
response.error(error)
},
useMasterKey: true
}
);
response.success();
}
});
The answer from Jake T. has some good points. Based on his answer and your comment on the question, you could try something like this:
Parse.Cloud.beforeSave('Order', function(request, response) {
var currentUser = request.object.get('user');
currentUser.fetch({useMasterKey: true}).then(function(user) {
var userLang = user.get('lang');
// send push notifications based on userLang here
response.success();
}).catch(function(error) {
// handle any errors here
console.error(error);
});
});
Verify you actually have a User object shell from request.object.get("user"); And, if you do, you can just call currentUser.fetch() instead of performing a query, unless there are other objects you may need to include.
Since you used a query, the result is an array, even if there is only a single object returned (or none, it would be simply []). So, you're doing Array.get("lang"), which shouldn't do anything. Try if( results && results.length > 0 ) user = results[0];, then you should be able to access user.get("lang");
You should have ACL / CLP's set up for your User class. Ideally, these should not be accessible by people who are not the user or master. So, if that is set up properly, your solution may be passing {useMasterKey:true} as an option to the query / fetch.
Can anyone tell what am I doing wrong here???
In bankbonejs, I am trying to make a POST request. Here is my code: Im using tomcat server.
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
saveDetails: function (ev) {
var abcDetails= $(ev.currentTarget).serializeObject();
var abc= new ABC();
bank.save(abcDetails, {
success: function (abc) {
router.navigate('', {trigger:true});
}
});
return false;
}
Call goes to the server side (Tomcat) but the post request params are coming as null. I have checked var abcDetails just before requesting the save has the values populated correctly. Also, checked by sending post request thru PostMaster to make sure that values are passed from the client side correctly. However, on the server side these posted request params are null. I am some how stuck here.vAppreciate help in this regard.
Server Side
.
#RequestMapping(value = { "/postedValues" }, method = RequestMethod.POST)
public String getpostedValues( HttpServletResponse response, HttpServletRequest request) throws Exception {
JSONArray jsonarray = new JSONArray();
JSONObject jsonobj = new JSONObject();
String _id = StringEscapeUtils.escapeHtml4(request.getParameter("id"));
String col1= StringEscapeUtils.escapeHtml4(request.getParameter("col1"));
String col2= StringEscapeUtils.escapeHtml4(request.getParameter("col2"));
Also,
Enumeration paramaterNames = request.getParameterNames();
while(paramaterNames.hasMoreElements() ) {
System.out.println(paramaterNames.nextElement());
}--> observation:does not go inside the while loop
I have created a store that attempts to do an AJAX request and set this.restaurants to the returned data. If I hard code the data in as an array of json to the `this.restaurants everything works great. But my AJAX call is not being run in time. How can i fix this? The console log displays everything as expected
class RestaurantStore extends EventEmitter {
constructor() {
super()
this.restaurants = this.getRestaurants()
}
getRestaurants() {
const url = `/lib/data/restaurants.json`
var r = new XMLHttpRequest();
r.open("GET", url, true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
const json = r.responseText
console.log(json)
return json
// this.restaurants = json
};
r.send();
}
}
I wrote some backend code for a Parse.com mobile app a couple of years ago, and have just been asked to add a feature. However, I found that after a small tweak the code wouldn't succeed. So, I rolled back to the working copy, downloaded, then deployed that back and it wouldn't work either! I wonder if this is a change in the Parse software?
The code is failing at the save method as all the logs are fine until then. The log for the error case shows 'No message provided'. If I don't use the message attribute it just shows '{}', so I presume it's empty. I have put the promise resolution in the error case to stop the job timing out while I debug. One thing I have never understood is why I have to make two Seed objects and piggy-back off one to save correctly. If I did a.save(null,...) it wouldn't work.
Any help would be fantastic. Thanks!
PS: Apologies for the indenting below - it is correct in my file.
function flush() {
//Clear the previous records from the class.
var Seed = Parse.Object.extend("Seeds");
var _ = require("underscore");
var arr = [];
var query = new Parse.Query(Seed);
return query.find().then(function(oldSeeds) {
_.each(oldSeeds, function(oldSeed) {
arr.push(oldSeed.destroy());
});
return Parse.Promise.when(arr);
});
}
Parse.Cloud.job("fetchjson", function(request, status) {
var url = 'someurl';
flush().then(function() { Parse.Cloud.httpRequest({url: url}).then(function(httpResponse){
var Seed = Parse.Object.extend("Seeds");
var jsonobj = JSON.parse(httpResponse.text);
var _ = require("underscore");
var results = [];
// do NOT iterate arrays with `for... in loops`
_.each(jsonobj.seeds, function(s) {
var p = new Parse.Promise();
results.push(p); // Needs to be done here or when() will execute immediately with no promises.
var seed = new Seed();
var a = new Seed(s);
var image_url = a.get("image")
//Get the JSON.
Parse.Cloud.httpRequest({url: image_url}).then(function(response) {
console.log("Fetching image at URL: " + image_url);
//Create a new image object and save, passing ref through promise.
var file = new Parse.File('thumb.jpg', { base64: response.buffer.toString('base64', 0, response.buffer.length) });
return file.save();
}).then(function(thumb) {
console.log("Attaching thumb to object");
//Set image ref as object attribute.
a.set("imageFile", thumb);
console.log("Parsing views into viewsint");
//Save decimal string as int into another attribute.
a.set("viewsInt", parseInt(a.get("views")));
console.log("Parsing description into descriptionarray");
//Save string as array into another attribute.
var dar = new Array(1);
//dar[0] = a.get("description")
a.set("descriptionarray", [a.get("description")]);
}, function(error) {
console.log("Error occurred :(");
}).then(function(){
console.log("Saving object");
//Save the object and resolve the promise so we can stop.
seed.save(a,{
success: function(successData){
console.log(successData);
p.resolve(successData);
},
error: function(error){
console.log(error.message);
p.resolve(error);
}
});
});
});
// .when waits for all promises to be resolved. This is async baby!
Parse.Promise.when(results).then(function(data){
console.log("All objects saved");
status.success("Updated Succesfully");
});
}, function(error) {
//Oh noes :'(
console.error('Request failed with response code ' + httpResponse.status);
status.error("Update Failed");
});
});
});
I changed your code a bit and put some comments to explain:
// DEFINE THESE ON THE TOP. NO NEED TO REPEAT.
var _ = require("underscore");
var Seed = Parse.Object.extend("Seeds");
function flush() {
//Clear the previous records from the class.
var arr = [];
var query = new Parse.Query(Seed);
return query.find().then(function(oldSeeds) {
_.each(oldSeeds, function(oldSeed) {
arr.push(oldSeed.destroy());
});
return Parse.Promise.when(arr);
});
}
Parse.Cloud.job("fetchjson", function(request, status) {
var url = 'someurl';
flush().then(function() {
Parse.Cloud.httpRequest({url: url}).then(function(httpResponse){
var jsonobj = JSON.parse(httpResponse.text);
var results = [];
_.each(jsonobj.seeds, function(s) {
// ONE SEED OBJECT WITH INITIAL SET OF DATA FROM JSON
var seed = new Seed(s);
var image_url = seed.get("image")
// A SERIAL PROMISE FOR EACH SEED
var promise = Parse.Cloud.httpRequest({url: image_url}).then(function(response) {
console.log("Fetching image at URL: " + image_url);
//Create a new image object and save, passing ref through promise.
var file = new Parse.File('thumb.jpg', { base64: response.buffer.toString('base64', 0, response.buffer.length) });
return file.save();
}).then(function(thumb) {
// SETTING MORE PROPERTIES
//Set image ref as object attribute.
console.log("Attaching thumb to object");
seed.set("imageFile", thumb);
//Save decimal string as int into another attribute.
console.log("Parsing views into viewsint");
seed.set("viewsInt", parseInt(seed.get("views")));
//Save string as array into another attribute.
console.log("Parsing description into descriptionarray");
seed.set("descriptionarray", [seed.get("description")]);
// SAVING THE OBJECT
console.log("Saving object");
return seed.save();
});
// PUSH THIS PROMISE TO THE ARRAY TO PERFORM IN PARALLEL
results.push(promise);
});
Parse.Promise.when(results).then(function(data){
console.log("All objects saved");
status.success("Updated Succesfully");
});
}, function(error) {
console.error('Request failed with response code ' + httpResponse.status);
status.error("Update Failed");
});
});
});
Thanks knshn. I had refactored the code a lot since that version (including several of the changes you made), but I had posted the version that was identical to that which was working fine before. Your changes let me see the right error. For some reason doing the simple single object implementation didn't work for me originally, hence the nasty workaround. It works now though.
I have now found the culprit - the Seed class had an attribute called 'id'. With the old version this worked fine, but when I deployed that code now it gave an error 101: 'object not found for update'. This must be because the new Parse code is mixing that up with the internal objectId and getting confused that the id is different to what it expects. I wonder how that could still work with the rollback though. Perhaps the at version was tagged to use the older Parse code.
My fix was to use a different name for the id - 'seed_id'.