Retrieve records using Fetch XML & Java Script

Goal: Retrieve entity data using FetchXML & Javascript

Process:

Step 1: download Xrm svc Toolkit, and download the Zip folder. Unzip XrmServiceToolkit the folder.

Step 2: Open the XrmServiceToolkit folder, you can find the below Javascript files.

  1. Jquery
  2. Json2
  3. XrmServiceToolkit
  4. XrmServiceToolkit.min

Continue reading “Retrieve records using Fetch XML & Java Script”

Populate user lookup from JavaScript

Populating lookup filed is little different than the normal attributes population in MSD 365. Here is the example of system user population with JavaScript.

Here are some related functions to get User’s (logged in user/ current user) information …

getUserId >> Xrm.Page.context.getUserId() is responsible to get the GUID of the SystemUser.Id value for the current user.

getUserName >> Xrm.Page.context.getUserName() is responsible to get a text string of the username / the current user.
getUserRoles >> Xrm.Page.context.getUserRoles() returns an array of strings that represent the GUID values of each of the security roles that the user is associated with or any teams that the user is associated with.

Setting User lookups

The common reason for retrieving the username and the user id is because both values are needed if you want to programmatically set a lookup field in CRM.

Example code is shown below

For MSD-365 V9, as many things are deprecated

function PopulateCurrentUser(executionContext) {
    //populate current user 
    var setUservalue = new Array();
    setUservalue[0] = new Object();

    var userSettings = Xrm.Utility.getGlobalContext().userSettings; // userSettings is an object with user information.

    setUservalue[0].entityType = 'systemuser';
    setUservalue[0].id = userSettings.userId; // The user's unique id
    setUservalue[0].name = userSettings.userName; // The user's name

    executionContext.getFormContext().getAttribute("soft_activeuser").setValue(setUservalue);
}

For earlier versions

//populate current user 
var setUservalue = new Array();
setUservalue[0] = new Object();
setUservalue[0].id = Xrm.Page.context.getUserId();
setUservalue[0].entityType = 'systemuser';
setUservalue[0].name = Xrm.Page.context.getUserName();

Xrm.Page.getAttribute("soft_lookupfieldName").setValue(setUservalue);
For more information explore on MSDN page – Client-side context (client-side reference)
That’s all.
Thanks.

Auto-Save Editable sub-grid

If you are working with editable grid, then there is a very common problem user faces that they always forget to save that grid and proceed further with the next business step on MSD 365 form.

The strange part is when the user makes some changes on the grid and saves the data, data won’t be saved but if they click on ‘Save and Close’ data gets saved. But with this user needs to open the same record again to proceed next. Continue reading “Auto-Save Editable sub-grid”

Colourful MSD View

color grid

Explanation:

  1. Create JavaScript library with below function code
  2.  Sample JavaScript Code
    function displayIconTooltip(rowData, userLCID) {
    
        var str = JSON.parse(rowData);
        var col_data = str.soft_fieldName_Value;
    
        var imgName = "";
        var tooltip = "{" + col_data + "}";
    
        switch (col_data) {
            case 1: //Fulfiled 
                imgName = "soft_Green";
                tooltip = "Fulfilled Completetly";
                $('span:contains("Fulfiled")').closest('tr').css('background-color', 'green');
                break;
            case 2: //Partial
                imgName = "soft_Yellow";
                tooltip = "Fulfilled Partialy";
                $('span:contains("Partial")').closest('tr').css('background-color', 'yellow');
                break;
            case 3: //Unfulfilled
                imgName = "No_colour";
                tooltip = "No fulfilled";
                $('span:contains("Unfulfilled")').closest('tr').css('background-color', 'white');
                break;
            case 4: // Cancelled 
                imgName = "soft_Red";
                tooltip = "Fulfilment Deactived/Cancelled";
                $('span:contains("Cancelled")').closest('tr').css('background-color', 'red');
                break;
    
            default:
                imgName = " ";
                tooltip = "N/A";
                break;
    
        }
        var resultarray = [imgName, tooltip];
        return resultarray;
    
    }
  3. then register that JavaScript on the view
  4.  Publish your changes  and hard refresh your browser
  5. … and done !!  🙂

Please note here is this will work only on Read Only View, not on the Editable View.

Thanks!

 

Refresh MSD form

Refresh-icon

When we need to refresh MSD CRM/365 form all the time, I mean whenever there is change on the record, the form has to refresh to populate new values. The workaround for this is, add ‘ModifiedOn’ field on the form and trigger below JavaScript function on change of it.  Continue reading “Refresh MSD form”

Fetch all parents who does not have child

free resorces

In one of scenario I was looking for all available Assets only, means show only those assets who are available for particular data range. Just like get all parents who does not have any child.

So, after some googling i found below way, but i was showing all booked and non booked assets for given date range.

Out of the box it wont give NOT-IN result, for it we need to change ‘Inner’ to ‘Outer’

<link-entity name="bookableresourcebooking" from="resource" to="bookableresourceid" link-type="outer" alias="aj">

Here is the complete sample fetch XML…..

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">

<entity name="bookableresource">

<attribute name="name" />

<attribute name="bookableresourceid" />

<order attribute="name" descending="false" />

<filter type="and">

<condition attribute="statecode" operator="eq" value="0" />

</filter>

<link-entity name="bookableresourcecategoryassn" from="resource" to="bookableresourceid" link-type="inner" alias="ai">

<filter type="and">

<condition attribute="resourcecategory" operator="eq" uiname="Backhoe" uitype="bookableresourcecategory" value="{798E6C02-3BBE-E711-8123-E0071B686A81}" />

</filter>

</link-entity>

<link-entity name="bookableresourcebooking" from="resource" to="bookableresourceid" link-type="outer" alias="aj">

<filter type="and">

<condition attribute="starttime" operator="on-or-after" value="2018-03-01" />

<condition attribute="endtime" operator="on-or-before" value="2018-03-31" />

<condition attribute="bookingstatus" operator="not-in">

<value uiname="Hard" uitype="bookingstatus">{6ABF1A73-DFB9-E711-8129-E0071B67C991}</value>

<value uiname="Soft" uitype="bookingstatus">{6BBF1A73-DFB9-E711-8129-E0071B67C991}</value>

</condition>

</filter>

</link-entity>

</entity>

</fetch>

 

But, it was not satisfactory one, as I was interested only for available assets. So with below little tweak its possible which include above tweak.

<condition entityname="bookableresourcebooking" attribute="resource" operator="null" />

and here is complete sample for it ….

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">

<entity name="bookableresource">

<attribute name="name" />

<attribute name="bookableresourceid" />

<order attribute="name" descending="false" />

<filter type="and">

<condition attribute="statecode" operator="eq" value="0" />

<condition entityname="bookableresourcebooking" attribute="resource" operator="null" />

</filter>

<link-entity name="bookableresourcecategoryassn" from="resource" to="bookableresourceid" link-type="inner" alias="ai">

<filter type="and">

<condition attribute="resourcecategory" operator="eq" uiname="Backhoe" uitype="bookableresourcecategory" value="{798E6C02-3BBE-E711-8123-E0071B686A81}" />

</filter>

</link-entity>

<link-entity name="bookableresourcebooking" from="resource" to="bookableresourceid" link-type="outer" alias="aj">

<filter type="and">

<condition attribute="starttime" operator="on-or-after" value="2018-03-01" />

<condition attribute="endtime" operator="on-or-before" value="2018-03-31" />

<condition attribute="bookingstatus" operator="not-in">

<value uiname="Hard" uitype="bookingstatus">{6ABF1A73-DFB9-E711-8129-E0071B67C991}</value>

<value uiname="Soft" uitype="bookingstatus">{6BBF1A73-DFB9-E711-8129-E0071B67C991}</value>

</condition>

</filter>

</link-entity>

</entity>

</fetch>

Simple one but it will save hours.

Thanks!!

Editable Grid: Make it read only

new things

We have a out the box option to make editable grid read only on the from it self but its applicable only for the views not for the sub-grids. Thus, with small JavaScript we can make it read only based on our business requirements. Here is the sample code for it

function setFieldsDisabled(context) {

    context.getFormContext().getData().getEntity().attributes.forEach(function (attr) {

        attr.controls.forEach(function (c) {

            if (c.getName("name") == "soft_ownercopy") {
                c.setDisabled(false);
            }
            else {
                c.setDisabled(true);
            }

        })

    });
    
}
 

Call it on where you want to…

js call

Thanks!!

Get data from selected rows of Sub-Grid

Here is the sample code to get desired data ( sample shows about GUIDS) from selected rows from the editable grid.

function GetSelecctedGuidsFromGrid() {

//Get an array of entity references for all selected rows in the subgrid
    var selectedEntityReferences = [];
    var sGuids = "";
 //get selected rows from grid    
var sRows = Xrm.Page.getControl("booked_asset").getGrid().getSelectedRows();
    
sRows.forEach(function (selectedRow, i) {
        selectedEntityReferences.push(selectedRow.getData().getEntity().getEntityReference());
    });
 //get all required data from each selected row    
for (let i = 0; i < selectedEntityReferences.length; i++) {
        if (sGuids == "") {
            sGuids = (selectedEntityReferences[i].id.toString());        
}
        else {
            sGuids = sGuids + "," + (selectedEntityReferences[i].id.toString());
        }    
}  
//clear field value    
Xrm.Page.getAttribute("soft_selectedassetlist").setValue(""); 
//set attribute value     
Xrm.Page.getAttribute("soft_selectedassetlist").setValue(sGuids);
    Xrm.Page.data.entity.save();
}

Thanks !!

Refresh Sub-Grid based on field value

Sometimes we need to refresh (or load data) MSD 365 sub-grid data based on some condition. This can be done with small JS, here is the sample code, its applicable to the editable grid as well….

But make sure that

  • The grid you are configuring is not set to ‘Related Records only’
  • You are configuring same entity which you querying in the query

ed grid

Here is the code ….

function FilterSubgridBasedOnField() {
var sGrid = window.parent.document.getElementById("Your_Grid_Name");
if (sGrid == null) {
alert("Grid is null");
setTimeout(function () { FilterSubgridBasedOnField(); }, 2000);
return;
 }
var fetchXml = [ "Your Fetch XML Query" ].join("");
if (sGrid.control != null) {
sGrid.control.SetParameter("fetchXml", fetchXml);
sGrid.control.refresh();
alert("Sub-Grid has updated with new data.");
 }
else {
setTimeout(FilterSubgridBasedOnField, 500);
}
}

Thanks !!

Call action with input & output parameters

Continue reading “Call action with input & output parameters”