Plugin throw customized error, unsaved changes are on form.

I have got one issue when I change some hidden fields on the CRM form and then I was executing the save code for CRM, on save there was one plugin running that throws some handled error message. Now I only get the “OK” and “Download Log” button.

Once i click OK button i still see some unsaved changes

For that if we don’t want to show the unsaved changes on the form below things we can do.

  1. Either find what are all the fields we have changes and set their initial values once you click the okay button (Note: we don’t have any click event given for this ‘OK’) button.
  2. Or some how set the form dirty = false on close of that pop up. (That is also not possible to achieve as we don’t have click/change event)

Solution for this situation would be as below :

  1. we can use save.then() function like below:

Xrm.Page.data.save().then(function (success) {
//This is success call back , do whatever you want to do. after save is done.
}, function (error) {
Xrm.Page.getAttribute(“FieldUniqueName”).setValue(Xrm.Page.getAttribute(“FieldUniqueName”).getInitialValue());

////Please note this getInitialValue only work for optionset and bool fields.
Xrm.Page.data.setFormDirty(false);
if (error && error.message) {
//This is the section where we get the error.message in the string format, we can show this in the formnotification.
} else {
// show default message if the error.message is empty or undefined.
}
});

Advertisements

How to Resize the window.showModelDialog after load of dialog.

Recently I got the requirement where, I had to show the Model dialog in small size and as per some conditions i need to adjust the size of the dialog, for that we need to use below

Resize function or dialogWidth and dialogHeight properties.

In other words dialogWidth and dialogHeight properties can help to adjust the width and height of the dialog. but if we need to do it in percentile increment then first we need to get the previous values and then do the addition and deletion in height and width.

 

Parent Page

<!DOCTYPE html>

<html>

<head>

https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js

</head>

<body>

<p>Click the button to open a new browser window.</p>

<button onclick=”myFunction()”>Try it</button>

function myFunction() {

window.showModalDialog(“./dialog.html”, “”, “dialogWidth:600px; dialogHeight:400px; center:yes; resizable:no”);

}

</body>

</html>

Dialog Html

<!DOCTYPE html>

<html>

<head>

https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js

$(document).ready(function(){

$(window).resize(function() {

window.dialogWidth = $(window).width() * 2;

window.dialogWidth = $(window).height() * 2;

});

$(window).trigger(‘resize’);

});

</head>

<body>

<p>Open a new window, and resize the width and height to 500px:</p>

</body>

</html>

or try this below html on demand height and width setting.

 

<!DOCTYPE html>

<html>

<head>

https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js

function ResizeNow(){

window.dialogWidth = $(window).width() * 2;

window.dialogWidth = $(window).height() * 2;

}

</head>

<body>

<button onclick=”ResizeNow()”>Resize Now</button>

<p>Open a new window, and resize the width and height to 500px:</p>

</body>

</html>

How to Resize the window.showModelDialog after load of dialog.

Recently I got the requirement where, I had to show the Model dialog in small size and as per some conditions i need to adjust the size of the dialog, for that we need to use below

Resize function or dialogWidth and dialogHeight properties.

In other words dialogWidth and dialogHeight properties can help to adjust the width and height of the dialog. but if we need to do it in percentile increment then first we need to get the previous values and then do the addition and deletion in height and width.

 

Parent Page

<!DOCTYPE html>
<html>
<head>
https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
</head>
<body>

<p>Click the button to open a new browser window.</p>

<button onclick=”myFunction()”>Try it</button>

function myFunction() {
window.showModalDialog(“./dialog.html”, “”, “dialogWidth:600px; dialogHeight:400px; center:yes; resizable:no”);
}

</body>
</html>

Dialog Html

<!DOCTYPE html>
<html>
<head>
https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js

$(document).ready(function(){

$(window).resize(function() {
window.dialogWidth = $(window).width() * 2;
window.dialogWidth = $(window).height() * 2;
});

$(window).trigger(‘resize’);

});

</head>
<body>

<p>Open a new window, and resize the width and height to 500px:</p>

</body>
</html>

or try this below html on demand height and width setting.

 

<!DOCTYPE html>
<html>
<head>
https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js

function ResizeNow(){

window.dialogWidth = $(window).width() * 2;
window.dialogWidth = $(window).height() * 2;
}

</head>
<body>
<button onclick=”ResizeNow()”>Resize Now</button>
<p>Open a new window, and resize the width and height to 500px:</p>

</body>
</html>

Javascript calls action in CRM

//this function is responsible to set the headers

var setRequestHeaders = function (req, includeFormattedValues, customHeaders) {
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”);
if (!(includeFormattedValues !== undefined && includeFormattedValues !== null && includeFormattedValues === false)) {
req.setRequestHeader(“Prefer”, “odata.include-annotations=\”OData.Community.Display.V1.FormattedValue\””);
}

if (!(customHeaders && customHeaders.constructor === [].constructor)) {
customHeaders = [];
}
customHeaders.forEach(function (h) {
switch (h.key) {
case “Accept”:
case “Content-Type”:
case “OData-MaxVersion”:
case “OData-Version”:
case “Prefer”:
break;
default:
req.setRequestHeader(h.key, h.value);
break;
}
});
},

 

// function name
stringParameterCheck = function (parameter, message) {
if (typeof parameter !== “string”) {
throw new Error(message);
}
},

//Async function

executeCustomAction = function (entityId, entityCollectionName, actionName, parameters, isGlobleAction, successCallback, errorCallback, customHeaders) {
var query = “”, req = “”;
stringParameterCheck(actionName, “MisXrmUtilities.WebAPI.executeCustomAction requires the actionName parameter is a string.”);

if (isGlobleAction !== undefined && isGlobleAction !== null && isGlobleAction !== true) {
stringParameterCheck(entityId, “MisXrmUtilities.WebAPI.executeCustomAction requires the e entityId parameter is a string.”);
stringParameterCheck(entityCollectionName, “MisXrmUtilities.WebAPI.executeCustomAction requires the entityCollectionName parameter is a string.”);
entityId = entityId.replace(“{“, “”).replace(“}”, “”);
query = entityCollectionName + “(” + entityId + “)/Microsoft.Dynamics.CRM.” + actionName;
}
else {
query = actionName;
}

req = new XMLHttpRequest();
req.open(“POST”, getWebAPIPath() + query, true);
setRequestHeaders(req, false, customHeaders);
req.onreadystatechange = function () {
if (this.readyState == 4) {
req.onreadystatechange = null;
switch (this.status) {
case 200:
successCallback(JSON.parse(this.response));
break;
case 204:
case 1223:
successCallback();
break;
default:
errorCallback(JSON.parse(this.response).error);
break;
}

}
};

req.send((parameters !== undefined && parameters !== null) ? JSON.stringify(parameters) : null);
},

 
//==============How to use this function==================//
parametersInJsonFormate = {
ActionInputParameter1: “here is the input”, // Make sure the name maches with the action input parameters
ActionInputParameter2: “anything can be passed”
};
executeCustomAction(entityId, entityCollectionName, actionName, parametersInJsonFormate, false, function(success){
//Success call back
}, function(error){

//Error call back
});

Calculate Date Difference in any intervals

function getDateDiff (date1, date2, interval) {
var second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24,
week = day * 7,
timediff;
date1 = new Date(date1).getTime();
date2 = (date2 == ‘now’) ? new Date().getTime() : new Date(date2).getTime();
timediff = date2 – date1;
if (isNaN(timediff)) return NaN;
switch (interval) {
case “years”:
alert(new Date(date2).getFullYear());
alert(new Date(date1).getFullYear());
return new Date(date2).getFullYear() – new Date(date1).getFullYear();
case “months”:
return ((new Date(date2).getFullYear() * 12 + new Date(date2).getMonth()) – (new Date(date1).getFullYear() * 12 + new Date(date1).getMonth()));
case “weeks”:
return Math.floor(timediff / week);
case “days”:
return Math.floor(timediff / day);
case “hours”:
return Math.floor(timediff / hour);
case “minutes”:
return Math.floor(timediff / minute);
case “seconds”:
return Math.floor(timediff / second);
default:
return undefined;
}
}

//————————————-

usage:

alert(getDateDiff(‘2016-03-16T23:00:00’, ‘2016-03-18’, ‘hours’));

alert(getDateDiff(‘2016-03-16T23:00:00’, ‘2016-03-18’, ‘weeks’));

alert(getDateDiff(‘2016-03-16T23:00:00’, ‘2016-03-18’, ‘days’));

How to send parameters in window.showModelDialog

openPopoutPage = function (pageName, height, width) {
var url = Xrm.Page.context.getClientUrl() + “//WebResources/mis_/” +
pageName +”?Data=” + encodeURIComponent(“id=” + Xrm.Page.data.entity.getId() + “&pname=” +
fullname.getValue() + “&gender=” + genderCode.getValue()),
sFeatures = “dialogHeight: ” + height + “px;”;
sFeatures = sFeatures + “dialogWidth: ” + width + “px;”;
sFeatures = sFeatures + “resizable: yes”;

window.showModalDialog(url, “”, sFeatures);
},

Get this passed parameters in json object

by below function

 

CommonUtility = (function () {
var getUrlQueryStringValues = function () {
var vars = [],
queryStringValues = window.location.href.slice(window.location.href.indexOf(‘?’) + 1).split(‘=’),
hash,
hashes,
i = 0;

if (queryStringValues.length === 2) {
if (queryStringValues[0].toLowerCase() === “data”) {
hashes = decodeURIComponent(queryStringValues[1]).split(“&”);

for (i = 0; i < hashes.length; i += 1) {
hash = hashes[i].split(‘=’);
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
}
}
return vars;
}

How to use this function

var queryParam= {};

queryParam= CommonUtility.getUrlQueryStringValues();

queryParam.id and queryParam.pname