My Photo

Microsoft Dynamics 365

Official Blog for Microsoft Dynamics Functional and Technical Solutions....
Browsing Category " advance javascript "

Telerik Kendo UI: Get sum and average of selected items of a grid in alert / Field / popup for specific columns

Scenario:

Recently we were having a requirement to get sum and average of selected items on a grid in either an alert / Field or popup
Such as in the below example I want to get the average and Sum of selected Frieght columns

And also we wanted to allow this feature only on numeric fields. 

Solution:

We were able to archive the desired result by using the change event, select and the dataItem methods to get the value of the selected cells. Then we used column index to get the selected column. And to restrict the calculation only for numeric column we programmatically remove the k-state-selected class from the desired cells.

Code Snippet :

<script> $(document).ready(function () { $("#grid").kendoGrid({ dataSource: { type: "odata", transport: { read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders" }, schema: { model: { fields: { OrderID: { type: "number" }, Freight: { type: "number" }, ShipName: { type: "string" }, OrderDate: { type: "date" }, ShipCity: { type: "string" } } } }, pageSize: 20 }, height: 550, filterable: true, sortable: true, pageable: true, selectable: "multiple cell", columns: [{ field: "OrderID", filterable: false, selectable: false }, "Freight", { field: "OrderDate", title: "Order Date", format: "{0:MM/dd/yyyy}", selectable: false }, { field: "ShipName", title: "Ship Name", selectable: false }, { field: "ShipCity", title: "Ship City", selectable: false } ] }); var grid = $("#grid").data("kendoGrid"); grid.bind("change", grid_change); }); function grid_change(e) { debugger; var selectedCells = this.select(); var cellOne = selectedCells[0] var colIdx = this.select().index(); var colName = $('#grid').find('th').eq(colIdx).text() if (colName === "Freight") { // execute only for number columns var selectedDataItems = []; var sumOfSelectedItems = 0; var averageOfSelectedItems = 0; for (var i = 0; i < selectedCells.length; i++) { var dataItem = this.dataItem(selectedCells[i].parentNode); if ($.inArray(dataItem, selectedDataItems) < 0) { selectedDataItems.push(dataItem); } } for (let i = 0; i < selectedDataItems.length; i++) { sumOfSelectedItems += parseFloat(selectedDataItems[i].Freight); } averageOfSelectedItems = sumOfSelectedItems / (selectedDataItems.length); averageOfSelectedItems = parseFloat(averageOfSelectedItems); alert("Sum : "+ sumOfSelectedItems.toFixed(2)); alert("Average : " + averageOfSelectedItems.toFixed(2)); $("#sumvalue").empty(); $("#sumvalue").append(sumOfSelectedItems.toFixed(2)); $("#Averagevalue").empty(); $("#Averagevalue").append(averageOfSelectedItems.toFixed(2)); $("#calculatedFields").show(); } } </script> </head> <body> <div class="container-fluid"> <div class="row k-header"> <h1> My App</h1> </div> </div> <div class="container-fluid"> <div class="demo-section k-content"> <div id="calculatedFields" style='float: left; display:none;'> <div style='float: left; margin-right: 30px;'> <span id="lblSum"> Sum : </span> <label id="sumvalue"></label> </div> <div style='float: left; margin-right: 30px;'> <span id="lblAverage">Average : </span> <label id="Averagevalue"></label> </div> </div> </div> <div> <div class="row"> <div class="col-xs-18 col-md-12"> <div id="grid"></div> </div> </div> </div> </div> <div class="container-fluid"> <div class="row"> <div class="col-xs-18 col-md-12"> <div id="grid"></div> </div> </div> </div> </body> </html>

Demo URL :

For your reference I made an example demonstrating this requirement :
 https://dojo.telerik.com/@Shashank%20Binjola/EtEwe


Other Useful URLs:

https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/events/change#change

https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/select

https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/dataitem

Hope It Helps 😊

Happy Coding ✌
SOURCE : mscrm.com

Create and Send Email Message Activity from javascript using api D365 / MS CRM 2016

For Creating email message activity from java script MS CRM , you can update and use the below code according to your requirement. Here to show I have taken up a scenario to send a email to system user when a Quote is won.

Replace the User GUID for to and from user in "fromFieldIdSystemAdmin" and  "toPartyUsersId"

function CreateEmail() {
    var fromFieldIdSystemAdmin = "53536B3D-4D71-4FC2-857C-0477750A92BE"; //todo Email from User GUID
    var toPartyUsersId = ["53536B3D-4D71-4FC2-857C-0477750A92BE"]; //todo Email To user array
    var quoteId = Xrm.Page.data.entity.getId();
    quoteId = quoteId.replace(/[{}]/g, "");
    var customerLookUp = Xrm.Page.getAttribute("customerid");
    var accountName = null;
    if (customerLookUp != null)
        accountName = customerLookUp.getValue()[0].name;
    var webapiPath = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/emails";
    var email = {};
    //Lookup
    email["regardingobjectid_quote@odata.bind"] = "/quotes(" + quoteId + ")"; //Regarding is quote
    email["subject"] = "Quote Sent ";
    email["description"] = "See attachment for the Quote that was set as Won";
    var parties = [];
    //ActivityParty (From)
    var sender = {};
    sender["partyid_systemuser@odata.bind"] = "/systemusers(" + fromFieldIdSystemAdmin + ")";
    sender["participationtypemask"] = 1; //From
    parties.push(sender);
    for (i = 0; i < toPartyUsersId.length; i++) {
        var receiver = {};
        receiver["partyid_systemuser@odata.bind"] = "/systemusers(" + toPartyUsersId[i] + ")";
        receiver["participationtypemask"] = 2; //To
        parties.push(receiver);
    }
    email["email_activity_parties"] = parties;
    var service = new XMLHttpRequest();
    service.open("POST", webapiPath, false);
    service.setRequestHeader("Accept", "application/json");
    service.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    service.setRequestHeader("OData-MaxVersion", "4.0");
    service.setRequestHeader("OData-Version", "4.0");
    service.send(JSON.stringify(email));
    if (service.readyState == 4) {
        if (service.status == 204) {
            var uri = service.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var emailGblId = matches[1];
            SendEmail(emailGblId);
        } else {

            Xrm.Utility.alertDialog(this.statusText);
        }
    }
}

function SendEmail(emailGblId) {
    var parameters = {};
    parameters.IssueSend = true;
    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/emails(" + emailGblId + ")/Microsoft.Dynamics.CRM.SendEmail", 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.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var results = JSON.parse(this.response);
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send(JSON.stringify(parameters));
}

function successCallback() {
}
function errorCallback() {
}
Happy Coding 😊


SOURCE : mscrm.com

Set only contact entity or only Account entity customer field lookup in case / Opportunity for ms crm

Set potential customer look up field to only for contact entity record.

By default out of the box functionality gave a pop up with two entity type -contact & account for customer lookup field ,
if your requirement is to set only contact or only account as entity it can be done using javascript as given below ,

Both Contact and Account are viewed by Default 

Get Form Type And Save Modes using JavaScript in mscrm 2011 , mscrm 2013 , mscrm 2015


getSaveMode() : Its Return a value telling what was the save event of ms crm entity record ( like is it due to deactivation of form , manual save or save and close etc) below is the full list of events .

// Code
execObj.getEventArgs().getSaveMode();


Event ModeValue
Save1
Save and Close2
Deactivate5
Reactivate6
Send (Email)7
Disqualify (Lead)15
Qualify (Lead)16
Assign (user or team owned entities)47
Save as Completed (Activities)58
Save and New59
AutoSave70
getFormType() :  Its Return a value Telling about form type of ms crm entity record ( Update , or create etc) , below is the full list of events.

Get Difference in days between two date fields using javascript ( differences between dates )

Hello , below you will find function calculating difference in days between two field using java script .

function diffrenceindays() {
    var startdate = GetDateValue(startfield);
    var Enddate = GetDateValue(endfield);

    var oneday = 1000 * 60 * 60 * 24;
    var differenceInDays = ((Enddate - startdate) / oneday);
    if (differenceInDays < 0) {
        alert(" date cannot be less then start date");

    }
    alert(" diffrence in days  " + differenceInDays);

}

function GetDateValue(field) {


    var year = field.getFullYear();
    var month = field.getMonth();
    var day = field.getDate();
    dateOnly = new Date(year, month, day);
    return dateOnly;


}





SOURCE : JUST2CODE.IN Subscribe to our YouTube channel : https://www.youtube.com/user/TheRussell2012