Subgrid data retrival in crm - javascript

I have a sub-grid dynamics 365 crm named competitors I have to get data from that sub-grid and print it into alert. I have searched in the net but every solution I get from there when I used is throwing error as deprecated method. How can I get the sub-grid data in dynamics 365 application using JavaScript. Can anyone provide sample code for that.
Thanks in advance

Here is below code I tried in one of my Instance. Considering you want alert on Opportunity entity and that too onload of a form.
Use Debugger and you will get the data.
function onLoad(executionContext){
debugger;
var formContext = executionContext.getFormContext();
var formType= formContext.ui.getFormType();
if(formType && formType!==1 && formContext.data.entity.getId()){
retreiveOppCompRecords(formContext.data.entity.getId().replace(/[{}]/g, "")).then(
function success(result) {
if(result.entities.length > 0){
for(i=0;i<result.entities.length;i++){
}
}
},
function (error) {
var alertStrings = {
confirmButtonLabel: "OK",
text: 'Failed at Function: enableDisableExpiryDate with error: ' + error.message
};
var alertOptions = {
height: 250,
width: 450
};
Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);
}
);
}
}
function retreiveOppCompRecords(recordId){
var fetchxml = ['<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">',
'<entity name="opportunity" >',
'<attribute name="name" />',
'<filter type="and" >',
'<condition attribute="opportunityid" operator="eq" value="' + recordId + '" />',
'</filter>',
'<link-entity name="opportunitycompetitors" from="opportunityid" to="opportunityid" alias="OppCompetitor" intersect="true" >',
'<link-entity name="competitor" from="competitorid" to="competitorid" link-type="inner" alias="Competitor" >',
'<attribute name="websiteurl" alias="CompetitorWebsite" />',
'<attribute name="name" alias="CompetitoName" />',
'</link-entity>',
'</link-entity>',
'</entity>',
'</fetch>'].join("");
fetchxml = "?fetchXml=" + encodeURIComponent(fetchxml);
return Xrm.WebApi.retrieveMultipleRecords("opportunity", fetchxml);
}

As AnkUser has eluded to you need to retrieve the associated records from your subgrid adding in the <attribute name=''> tags as needed for the columns you need.
Remember a sub-grid is simply a view of data, usually, associated with the given record.
What specifically are you trying to retrieve from the subgrid?

I found my answer already - I have added an onload event to subgrid via JavaScript and retrieved data using Xrm.Page.getControl(“entityname”).getGrid().

Related

Retrieve specific data stored with JSON

I've used the code posted in THIS STACKOVERFLOW POST to build a prototype of a webbapp, but I can't make the second page show me the data with the format I want.
The code shows me the second page with all the data in a grid format, but I want to know how to make specific data with different formats (bold, italic, color).
For example, one string that I use is a "image.jpg" text to load an image of the user.
I've modified the first part of the code to:
$.each(info, function (i, valor) {
li += '<li><img src="img/'+ valor.foto +'"><h2><i>' + valor.cientifico + '</i></h2><p><b>Familia:</b> <i>'+ valor.familia +'</i> | <b>Subfamilia:</b> <i>'+ valor.subfamilia +'</i></p></li>';
});
to add specific values and apply different format (familia, subfamilia) and to insert the picture with the "foto" value.
Then the code continues:
$("#lista").append(li).promise().done(function () {
$(this).on("click", ".info-go", function (e) {
e.preventDefault();
$("#resultado").data("info", info[this.id]);
$.mobile.changePage("#resultado");
});
$(this).listview("refresh");
});
});
$(document).on("pagebeforeshow", "#resultado", function () {
var info = $(this).data("info");
var info_view = "";
for (var key in info) {
info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
}
$(this).find("[data-role=content]").html(info_view);
});
I know that the for (var key in info) is not what I'm looking for, but I don't know what code I have to use because I'm too new to unsderstand how to do it. How can I accomplish this?
The code next to info_view is HTML, right, but if I replace + key + with + familia + for example this doesnt works like before.
My question is how can I make to retrieve an specific data (for example the foto value) of the selected item listed in the first page? I want to be able to select wich items use. For example, I wanna make the id value invisible for the user, make the id value invisible, the name value in bold, and so on
Hope I was enough clear, sorry for my limited english and coding knowledge
Finnaly I've solved my own question.
For reference, what I do was deleted the
for (var key in info) {
and inside the info_view += part i've used info['value'] for each item I want to manipulate.
Hope this helps someone else.

referring to specific parts of a python dictionary in javascript

I made a program which parses data and then does a python json.dumps() with it. Next, in my javascript, I did a jQuery getJSON() with this data.
Before I did the json.dumps() with my data, I split it into three list because I didn't know how to deal with the data in js. The data is structured like this:
Key: (value1, value2)
I simply need to refer to those individual 'columns' in my javascript separately. I feel like it might be more efficient to just do the dumps() with the python dictionary but I don't know how to refer to it as I want in the javascript. Obviously it's important that the data stay "grouped"
How would I go about doing that?
Here's a full example that I have used in a mapping project. Javascript loads data via Ajax from the flask application.
The JQuery ajax method is very similar to the getJSON method.
#ajax method to retreive well data for dynamic well values, x_pos, y_pos, substance concentration
#app.route('/getWellData', methods=['GET', 'POST'])
def getWellData():
#get all samples with that date
date_collected = request.args.get('date_collected')
site_id = request.args.get('site_id')
site_map_id = request.args.get('site_map_id')
substance_id = request.args.get('substance_id')
well_results = wellSubstanceDataBySite(
site_id=site_id,
site_map_id=site_map_id,
date_collected=date_collected,
substance_id=substance_id)
#return json to updateMarks ajax javascript function
return json.dumps(well_results)
Javascript:
//call the ajax endpoint for getWellData to return position, values, etc
$.ajax({
dataType: "json",
url: '/getWellData',
data: data,
success: function(data){
//iterate over each value in the data array and append it as div element to the .landmarks div
$.each(data, function(well_id, well){
//create the mark element, must be all mashed into one line, wont work with multiple lines
//sutract depth_of_water (well.value) from well.top_of_casing
var goundwater_elevation_val = well.top_of_casing - well.value
var mark = '<div class="item mark" id="well-' + well_id + '" data-id="' + well_id + '" data-position="' + well.xpos + "," + well.ypos + '" data-value="' + goundwater_elevation_val.toFixed(4) + '" data-show-at-zoom="0"><div><div class="text"><input class="well-checkboxes" type="checkbox" name="enable-well-' + well_id + '" checked style="margin:3px;"><strong>' + goundwater_elevation_val.toFixed(4) + '</strong></div><img src="/static/jquery-image-viewer/example/images/mark.png" width="50px" height="50px" alt="Permanent Mark" /></div></div>';
if (well.value != 0) {
//append the new mark to the .landmarks div
$('.landmarks').append(mark);
}
});
//refresh all landmarks to plot the new landmarks on the map with the smoothZoom API
$('#sitemap').smoothZoom('refreshAllLandmarks');
}
});

Change MSCRM 2011 subgrid entity

I know how to modify the FetchXml of the subgrid. I'm attempting to dynamically change a subgrid based on selections from optionsets with JS. Based on the optionsets, the subgrid will need to be able to display different entities (not at the same time).
Example: The subgrid is currently showing Accounts with a specific relationship type. An optionset changes and now the subgrid should show Leads whose first name is John.
The error I'm receiving is "Entity Name specified in FetchXml does not match the entity name in the EntityExpression"
I feed the below fetch into the grid. It's just a multi-value search. rc_entitylist contains all entities in the system. rc_attributelist contains all the fields for the selected entity. The user selects an entity, selects a field to search, enters search criteria (one value per line) and then it populates the subgrid accordingly.
function runSearch() {
var entityname = Xrm.Page.getAttribute("rc_entitylist").getText();
var sgrid = "searchResults";
var fetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">'+
'<entity name="' + entityname + '">'+
'<all-attributes />' +
'<filter type="and">'+
'<filter type="or">';
var textBoxLines = document.getElementById("rc_searchcriteria").innerText;
var attributename = Xrm.Page.getAttribute("rc_attributelist").getText();
var lines = textBoxLines.split(/\n/);
for(var i=0;i < lines.length; i++){
fetchXml = fetchXml + '<condition attribute="' + attributename + '" operator="eq" value="'+ lines[i] +'" />';
}
fetchXml = fetchXml + '</filter>'+
'</filter>'+
'</entity>'+
'</fetch>';
updateXml(sgrid, fetchXml, entityname);
}
function updateXml(grid, xmlfield, entityname) {
try {
var g = document.getElementById(grid).control;
g.setParameter("fetchXml", xmlfield);
} catch (e) { }
// Refresh the grid
document.getElementById(grid).control.refresh();
}
Have you thought about adding multiple subgrids to the form, and hiding/showing them based on the on-change event of the optionset?

perform a fetch query on html popup

I have created a html web resource that I am showing when a ribbon button is clicked. On this popup I have a drop down list that I want to populate with a list of records that I have obtained using a fetchXml query.
My problem is that I have tried a few different ways to execute the query but it always comes back with errors. I'm guessing that the popup wont have the same range of functions that the parent form will have and so I will need to do something different to execute the query.
Currently I have it so that I have loaded an external script containing the functions needed to perform the fetch, but the code cannot see the CRM function of _HtmlEncode, and therefore fails.
Is there any way that I can get the popup to see the CRM functions? Or is there an alternate way of doing this?
EDIT: Some sample code
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:asp>
<head>
<title>Re-Assign</title>
<script type=text/javascript src="ClientGlobalContext.js.aspx"></script>
<script type=text/javascript src="http://crm/DEVCRM/WebResources:ts_/scripts/fetch_global.js"></script>
<script type=text/javascript>
function OnLoad_GetAreasAndConsultants() {
var fetchXml = '<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0"><entity name="ts_solution_area"><attribute name="ts_solution_areaid"/><attribute name="ts_descriptor"/><attribute name="createdon"/> <order descending="false" attribute="ts_descriptor"/><filter type="and"><condition attribute="statecode" value="0" operator="eq"/></filter></entity></fetch>';
var fetchedRecords = FetchRecordsToolKit.Fetch(fetchXml);
if (fetchedRecords !== null) {
var areaList = document.getElementById("ddl_solution_area")
for (var i=0; i<fetchedRecords.length;i++) {
var name = fetchedRecords[i].getValue("ts_descriptor");
areaList.options[select.options.length] = new Option(name, i);
}
}
}
</script>
Thanks
I built something specifically for executing fetch within an HTML web resource.
https://github.com/paul-way/JCL/blob/master/jcl.js
Here's an example of using it:
var processProjectInfo = function (data) {
if (data.length > 0) {
// Set Project Header Information
$('#ProjectTitle').html(data[0].attributes.new_name.value);
$('#CompanyName').html(data[0].attributes.new_accountid.name);
}
};
var loadProjectInfo = function (guid) {
var fetchXML = " " +
"<fetch mapping='logical' count='10'>" +
" <entity name='new_project'>" +
" <all-attributes/>" +
" <filter>" +
" <condition attribute='new_projectid' operator='eq' value='" + guid + "' />" +
" </filter>" +
" </entity>" +
"</fetch>";
JCL.Fetch(fetchXML, processProjectInfo);
};

Determine if an element is exists

Am creating a comment system for a web app, the comments are loaded when a user clicks on the comment image, html code is dynamically generated with json to display the comments.
But when the image is clicked again,the request is made again populate the page with the same data
Heres my code
function latest_pheeds() {
var action = url+"pheeds/latest_pheeds";
$.getJSON(action,function(data) {
$.each(data,function(index,item) {
$('#pheed-stream').append
(
'<div class="pheed" id="'+item.pheed_id+'">'+
'<p>'+item.user_id+'</p>'+
'<p>'+item.pheed+'</p>'+
'<div class="pheed_meta">'+
'<span>'+item.datetime+' Ago</span>'+
'<span>'+item.comments+
'<img class="comment_trigger" src="/pheedbak/assets/img/comment.png" title="Click to comment on pheed" onclick="retrieve_comments('+item.pheed_id+')">'+
'</span>'+
'</div>'+
'</div>'
);
});
});
}
function retrieve_comments(pheed_id) {
var action = url+'comments/get_comments';
var crsf = $('input[name=ci_csrf_token]').val();
var dataString = "pheed_id="+pheed_id+"&ci_csrf_token="+crsf;
$.ajax({
url:action,
type:'POST',
cache:false,
dataType:'json',
data:dataString,
success:function(data) {
$.each(data,function(index,item) {
$("#" + pheed_id).append(
'<div class="pheed_comments">'+
'<div class="comment">'
+'<span><p>'+item.user+'</p></span>'
+item.comment+
'</div>'+
'</div>'+
'<div id="comment_box">'+
'<textarea id="comment" cols="30">'+
'</textarea><br>'+
'<input type="button" class="submit_btn" value="comment" />'+
'</div>'
);
});
}
});
}
latest_pheeds() loads the pheeds and retrieve_comments gets the comments of the pheed_id passed to it.
How do i determine if the comment area has already been populated and instead update it with new comments if available. Thanks
Check for
$("#" + pheed_id +' .pheed_comments').length
if will be 0 if the element(I guess vou mean div.pheed_comments ) doesn't exist.
Several choices:
1) If you already have all the comments from your ajax call, then just remove the previous comments you have from the DOM and insert everything you just got.
2) If you have an ajax call that can retrieve just the new comments, then you can just check the DOM to see if you already have comments in the DOM and then just request new comments after some token in time (that you would have previously saved). When you receive the new comments, you would append them to what you have.
$('#pheed-stream').children().length will tell you how many children there are in the pheed-stream hierarchy. If that's zero, you haven't done any pheeds yet.
I would suggest that it's probably easiest to just retrieve all the comments and replace everything you have with the new list of comments than to try to retrieve just the new comments. Retrieving just the new comments will require some sort of time token that you can give the server so it knows which "new comments" to give you.
$("#" + pheed_id + " .pheed_comments").length will tell you whether any comments have been retrieved yet for that pheed_id.
you are adding div with id. Just check if it exists. If yes, then update it, otherwise insert.

Categories