Hello,
You will have to call this function on your opportunity form, when you change the account field this function has to be called, it will check if the selected account has more than 10 opportunities:
function checkNumberOfOpportunities()
{
var lookupObj = Xrm.Page.getAttribute(lookupSchemaName); //Check for Lookup Object
if (lookupObj != null) {
var lookupObjValue = lookupObj.getValue();//Check for Lookup Value
if (lookupObjValue != null) {
var lookupEntityType = lookupObjValue[0].entityType, //To get EntityName
lookupRecordGuid = lookupObjValue[0].id, // To get record GUID
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: Xrm.Page.context.getClientUrl() + "/api/data/v9.0/opportunities?$select=_accountid_value&$filter=_accountid_value eq "+lookupRecordGuid+"",
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations=\"*\",odata.maxpagesize=10");
},
async: true,
success: function(data, textStatus, xhr) {
var results = data;
for (var i = 0; i < results.value.length; i++) {
if(results.value.length >= 10) Xrm.Utility.alertDialog("Account already has 10Opportunities");
}
},
error: function(xhr, textStatus, errorThrown) {
Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
}
});
}