Retrieve rows in crm2011 subgrid with JScript - dynamics-crm

As an JScript newbie, I have a problem with a subgrid in MS CRM 2011.
I have a form with a subgrid and in OnSave of that form, I want to loop over all the rows in the subgrid.
How can I do this with JScript ? Or is it possible another way, ex plugin ?
Thx

Here is the sample code which you can do on save of the form
var gridControl = document.getElementById('grdrelatedcontacts').control;
for (var intRowNumber = 0; intRowNumber < gridControl.getRecordsFromInnerGrid().length; intRowNumber++)
for (var intCellNumber = 0; intCellNumber < gridControl.getRecordsFromInnerGrid()[intRowNumber][3].cells.length; intCellNumber++)
alert(gridControl.getRecordsFromInnerGrid()[intRowNumber][3].cells[intCellNumber].outerText);

You can inspect the subgrid values on save by doing the following:
var gridControl = document.getElementById('subgrid_id').control;
var ids = gridControl.get_allRecordIds();
for(i = 0; i < ids.length; i++) {
var cellValue = gridControl.getCellValue('column_name', ids[i]);
// logic
}
Doing this on load is a bit more challenging since subgrids are loaded asynchronously and aren't likely to be done loading when the form onload event fires. You can check the grid periodically though to see when it's done loading by calling a function like the following in your form onload:
function subGridOnload() {
var grid = document.getElementById('subgrid_id');
if (grid.readyState!="complete") {
// delay one second and try again.
setTimeout(subGridOnload, 1000);
return;
}
// logic
}

Use a Rest call and retrieve the corresponding records :S

You can do something like this:
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/pws_streedandhousenodatas?$filter=_pws_streetandhousenumberid_value eq " + Xrm.Page.data.entity.getId(), true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var pws_streedandhousenodataid = results.value[i]["pws_streedandhousenodataid"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
In this case the Xrm.Page.data.entity.getId() get you your current record id and you are looking all the lookups (that are in the sub-grid), you can also add some fields to select more info from them.

Related

Problem with scope when inserting results of ajax call into page code

I have data returned from an Ajax call, but need to pass variables into or out of the Ajax onSuccess function to insert the results into my page. I'm pretty sure this is a scope problem.
I posted a complicated question here yesterday, mostly about the Ajax part of this, and that part is now working - I'm getting the results back correctly. I could insert it into my page code in two ways, but one involves getting a variable value out of the onSuccess function; the other needs to get a variable value into it! I can't make either of them work. Here's a stripped-down version of the code:
var base = 'http://10.0.1.2:90/~dvds/';
// initialization routines
document.observe ('dom:loaded', function() {
// set up handler for variable numbers of selects
var addselects = $$('.addselect');
for (var i = 0; i < addselects.length; i++) {
var addselect = addselects[i];
addselect.onchange = newSelect;
}
});
// handler for adding new field to array
function newSelect() {
var thisid = this.id;
var newhtml;
var url = base + 'ajaxtest';
// send request to do the business
var myAjax = new Ajax.Request (url, {
method: 'post',
onSuccess: function (req) {
var xml = req.responseXML;
var id = xml.getElementsByTagName('id')[0].firstChild.nodeValue;
if (id) {
newhtml = '\t\t<li>\r\t\t\t<select class="addselect" name="newlist" id="newlist" />\r\t\t\t\t<option value="" selected="selected"></option>\r';
// loop
var newid, newname;
var ids = xml.getElementsByTagName('id');
var names = xml.getElementsByTagName('name');
for (var i = 0; i < ids.length; i++) {
newid = ids[i].firstChild.nodeValue;
newname = names[i].firstChild.nodeValue;
newhtml += '\t\t\t\t<option value="' + newid + '">' + newname + '</option>\r';
}
newhtml += '\t\t\t</select>\r\t\t</li>\r';
// alert (thisid);
$('thisid').up('ul').insert (newhtml);
}
else {
alert (’ng');
newhtml = '<li>No good.</li>';
}
},
onFailure: function() {
alert ('Script failure.');
newhtml = '<li>No good.</li>';
}
});
// alert (newhtml);
// if (newhtml) {
// this.up('ul').insert (newhtml);
// }
}
Having established the variable thisid as this.id, I don't understand why $('thisid') doesn't work in the line $('thisid').up('ul').insert (newhtml); - especially as the value of thisid does show up correctly in the alert I've put in for testing (commented out). Why is this? If I put newhtml into that alert instead it's also correct.
And given that that seems not to work, I tried the alternative of passing the value of newhtml out (having declared it at the top) and inserting it in the page in the last block of code that's commented out - but that doesn’t work either.
Where am I going wrong?

how to get label of optionset in crm

I'm using D-CRM 2016 I'm trying to get a label of optionset in client-side (js) ,I get an error and can't find a reason why:
thats my code:
SDK.Metadata.RetrieveAttribute("myEntity", "myFieldName", null, false,
function (result) {
alert(result);
for (var i = 0; i < result.OptionSet.Options.length; i++) {
var loopText = result.OptionSet.Options[i].Label.LocalizedLabels[0].Label;
var loopValue = result.OptionSet.Options[i].Value;
}
},
function (error) { }
,false);
My error:
Uncaught TypeError: _Context(...).getServerUrl is not a function
at _getUrl (/SDev/%7B636656731400000359%7D/WebResources/xnes_SDK.MetaData?ver=1561501807:451)
at Object.RetrieveAttribute (/SDev/%7B636656731400000359%7D/WebResources/xnes_SDK.MetaData?ver=1561501807:323)
at <anonymous>:1:14
at Mscrm.CommandHandler.$Ce_1 (JsProvider.ashx:8)
at Mscrm.CommandHandler.$Ag_1 (JsProvider.ashx:8)
at Mscrm.CommandHandler.handleCommand (JsProvider.ashx:8)
at Mscrm.CommandBarData.executeCommand (JsProvider.ashx:8)
at Mscrm.ButtonControl.executeCommand (ribbon.js:1)
at Mscrm.ButtonControl.click (ribbon.js:1)
at Mscrm.CommandBar.onClickHandler (ribbon.js:1)
Anytime you're attempting to do client side rest calls, I always recommend Jason Lattimer's CRM Rest Builder (https://github.com/jlattimer/CRMRESTBuilder) You can access the text labels using the "Formatted Values" option.
The principal problem is with the SDK you are using. I can't really debug it for you.
However, here's a working sample that is returning the label and the value. There a header (Prefer) you can add to tell the api to return the label as well:
var odataEndPoint = Xrm.Page.context.getClientUrl() + '/api/data/v8.2/';
function GetDomainName(entityId) {
var result = null;
var req = new XMLHttpRequest();
req.open("GET", odataEndPoint + 'systemusers(' + TrimGuid(entityId) + ')/', false);
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.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
req.onreadystatechange = function () {
if (this.readyState == 4) {
req.onreadystatechange = null;
if (this.status == 200) {
if (this.response) {
result = JSON.parse(this.response);
}
}
else {
var parsed = JSON.parse(this.response);
console.error(parsed.error.message)
}
}
};
req.send();
return result;
};

AJAX Dynamic Buttons

Does anyone have suggestions on how to complete the following assignment? I've listed the instructions from the teacher below along with my JavaScript code. Thanks in advance!
Instructions:
The primary task is to dynamically generate the "genre" buttons that are currently hardcoded into the correlating HTML file.
The genre buttons should work the same way the hardcoded buttons currently work meaning they should have an event listener attached to them that should display podcasts from the ajax response that match the genre that was clicked.
JavaScript Code:
/**
* Ajax GET requester
*
*/
function get(url){
// Return a new promise.
return new Promise(function (resolve, reject){
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', 'js/data.json');
req.onload = function(){
// This is called even on 404 etc
// so check the status
if(req.status === 200){
// Resolve the promise with the response text
resolve(req.response);
}else{
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Make the request
req.send();
});
}
function get_podcasts(genre){
var url = 'js/data.json';
get(url).then(function (response){
var body = document.getElementById('mainContent');
response = JSON.parse(response);
if(response.results.length > 0){
body.innerHTML = '';
for(var i = 0; i < response.results.length; i++ ){
if(response.results[i].primaryGenreName === genre ){
var image = '<img src="' + response.results[i].artworkUrl100 + '">';
var image = document.createElement('img');
image.src = response.results[i].artworkUrl100;
body.appendChild(image);
body.innerHTML += '<div>' + response.results[i].trackName + '</div>' ;
}
}
}else{
body.innerHTML = 'No results found.';
}
console.log(response);
}, function (error){
console.log('No hits Found');
});
}
window.onload = function(){
//create an array with all button names
var genreNames = ['TV & Film', 'News & Politics', 'Society & Culture', 'Music', 'Hobbies'];
//loop through the array
for(var i = 0; i < genreNames.length; i++){
//create button element called "TV and Film" or whatever
var dynamicButtons = document.createElement('BUTTON');
var buttonText = document.createTextNode(genreNames);
//add it to the DOM (document)
dynamicButtons.appendChild(buttonText);
document.body.appendChild(dynamicButtons);
}
/*
for(i =0; i <= response.results.length; i++) {
for (key in response.results[i].primaryGenreName) {
if(response.results[i].primaryGenreName.hasOwnProperty(key)) {
output += '<li><button type="button">' + response.results[i].primaryGenreName + '</button></li>';
var update = document.getElementById('genres');
update.innerHTML = output;
}
}
}
*/
};

How to know if all uploads completed within a loop?

I have a code that works well for sending multiple files via ajax with FormData and XMLHttpRequest;
for (var i=0, j=this.files.length; i<j; i++) {
file = this.files[i];
var formdata = new FormData();
formdata.append("images[]", file);
var xhr = new XMLHttpRequest(),
upload = xhr.upload,
id = Math.floor((Math.random() * 100000));
upload.addEventListener("loadstart", function(e){
showUploadedItem(file, this.id);
});
upload.id = id;
upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
)
};
upload.onload = function(e) {
if (this.status == 200) {
console.log('');
}
};
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log('');
}
};
xhr.open('post', '<?php echo Yii::app()->createUrl('url') ?>', true);
xhr.send(formdata);
}
I am sending each file as a new XMLHttpRequest object inside the loop, so I do not know when I'm getting all requests ending.
Can anyone help?
Take a look at the documentation for XMLHttpRequest.
There are a couple of options that I can think of. You could use the "loadend" callback for each of them and increment a variable outside of the loop and check for the total amount of requests that were sent in each one. Once the count reaches the total number of requests, you could perform any logic or call a function that would want to call.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest?redirectlocale=en-US&redirectslug=DOM%2FXMLHttpRequest%2FUsing_XMLHttpRequest
Otherwise, setting the async parameter to false would work as well, but then you take a performance hit waiting for each one to finish before starting the others.
Based on your answer, my solution;
var x = 0;
var lenght = this.files.length;
for (var i=0, j=lenght; i<j; i++) {
// code here
var xhr = new XMLHttpRequest(),
// code here
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState && this.status == 200 ) {
x++;
if(x == lenght) {
window.setTimeout( function(){
alert('finish');
}, 1000 );
}
}
};
// code here
}
Though it is a trivial function, it works.

Adding a .ajaxForm function to standard .ajax call

So I'm trying to find a method of getting a progress bar working on my .ajax call but not having much luck. I know that the ajaxForm plugin has the following code in it that allows for the uploadProgress option but the way my code works I'm not able to use that plugin. Is there anyway of adding the following code somehow so that it attaches to the standard .ajax call? Long shot I know!
// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();
for (var i=0; i < a.length; i++) {
formdata.append(a[i].name, a[i].value);
}
if (options.extraData) {
var serializedData = deepSerialize(options.extraData);
for (i=0; i < serializedData.length; i++)
if (serializedData[i])
formdata.append(serializedData[i][0], serializedData[i][1]);
}
options.data = null;
var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: method || 'POST'
});
if (options.uploadProgress) {
// workaround because jqXHR does not expose upload property
s.xhr = function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
}, false);
}
return xhr;
};
}
s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function(xhr, o) {
o.data = formdata;
if(beforeSend)
beforeSend.call(this, xhr, o);
};
return $.ajax(s);
}
I do not guarantee on that, but try this:
xhr.upload.onprogress = function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
console.log("Progress: "+percent+"%"); //debug to see if the problem is there
options.uploadProgress(event, position, total, percent);
};
From posted code, I cannot even guess if the problem is in onprogress event handling or that options.uploadProgress, whatever it is.
I posted this as answer only because it wouldn't fit in comment.

Resources