My Photo

Microsoft Dynamics 365

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

Validation to accept only Numeric Character in MS CRM


Below script is a generic validation which will show for error if field is having anything except numeric value



function ValidateOnlyNumeric(context) {
    var fieldname = context.getEventSource().getName();
    var phone = Xrm.Page.getAttribute(fieldname).getValue();
    if (checkFormat(phone)) {
        Xrm.Page.getControl(fieldname).clearNotification();
    } else {
        Xrm.Page.getControl(fieldname).setNotification("Please enter only numeric characters");
    }
}
function checkFormat(phone) {
    var regex = /^\d+$/;
    if (regex.test(phone)) {
        return true;
    } else {
        return false;
    }
}

To enable it for any field just register it on change of the required field with function name “ValidateOnlyNumeric” and check “Pass execution context as first parameter ” and save an publish it will start working



Hope it helps

Happy Coding 😊

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

Xrm.Page.ui control (client-side reference)

SOURCE : msdn.microsoft.com

Xrm.Page.ui control (client-side reference)

Dynamics CRM 2013
This topic has not yet been rated Rate this topic
Applies To: Microsoft Dynamics CRM 2013, Microsoft Dynamics CRM Online
The control object provides methods to change the presentation or behavior of a control and identify the corresponding attribute.

Beginning JavaScript ms CRM 2011

Xrm.Page.context Methods

1. getAuthenticationHeader: 
Returns the encoded SOAP header necessary to use MSCRM 4.0 Web service calls.
2. getCurrentTheme:
Returns the current Outlook theme chosen by the user.
3.getOrgLcid:
Returns the LCID value for the base language of the organization.

How to Create Dynamic OptionSet in MS Dynamics CRM 2011 & 2013 dynamics365

How to Create Dynamic OptionSet in MS Dynamics CRM 2011 & 2013


This code will help you..................

function dynamicoptionset() {

//get value in no in variable
    var totaldivision = Xrm.Page.getAttribute("fieldname" ).getValue();
    if (totaldivision == null || totaldivision == "" )
        return;
    else {

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 all the Teams of User belong to using JavaScript (xml ) in ms crm 2011 , ms crm 2013 , ms crm 2015



Get all the Teams User belongs to.


var xml = "" +
 "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
 "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
 GenerateAuthenticationHeader() +
 " <soap:Body>" +
 " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
 " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
 " <q1:EntityName>team</q1:EntityName>" +
 " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
 " <q1:Attributes>" +

Get the CRM Organization URL using javascript in ms crm 2011 , ms crm 2013 , ms crm 2015


Retrieve the CRM Organization URL with respect to the current domain name. For example, if you are browsing the CRM instance with IP, then the return value would be like this: http(s)://<IP>/<OrgName>If you are browsing with domain name, it would be like this: http(s)://<DomainName>/<OrgName> 




function GetServerUrlRegExp(location) {
    var urlReg = new RegExp(/http[s]?:\/\/[0-9.:]+\/[^\/]+/);
    var ServerUrl = Xrm.Page.context.getServerUrl();
    if (window.location.href.match(urlReg) != null) {
        ServerUrl = window.location.href.match(urlReg).toString();
    }

Get Schema Names of the field ( Attribute ) using JavaScript in ms crm


To get the Schema Names of all the attributes or fields in given entity. 

function getSchemaNamesList(entityName) {
 var request = "<Request xsi:type='RetrieveEntityRequest'>" +
               "<MetadataId>00000000-0000-0000-0000-000000000000</MetadataId>" +
               "<EntityItems>IncludeAttributes</EntityItems>" +
               "<LogicalName>" + entityName + "</LogicalName>" +
               "<IsCustomizable>1</IsCustomizable>" +
               "<RetrieveAsIfPublished>true</RetrieveAsIfPublished>" +
               "</Request>";

New JavaScript function for ms crm 2011 , ms crm 2013 and ms crm 2015 , useful JavaScript method for Microsoft dynamics crm


        Below are the few useful properties, commands in ms crm 2011 ms crm 2013 and ms crm 2015 Javascript. You can work with them on form event say OnLoad.

Click on the item below to go through the description about that.
  • Get the string value of a Text field
  • Set the string value of a Text field
  • Retrieve Optionset Value/Text
  • Get the label name of the field
  • Get Lookup field name(value)
  • Get Lookup field ID
  • Get current entity name
  • Get Type Code of lookup
  • Get reference entity name of lookup
  • Set Lookup field
  • Get Event generated field value
  • Get Organization Name
  • Get Organization Language Code
  • Get Server URL
  • Check for Dirty
  • Get GUID of current record
  • Whether the field is disabled or not
  • Get form type
  • Get required fields in the form
  • Save the current record
  • Save the current record
  • Set focus on the field
  • Hide a field on the form
  • Disable(Read only) and Enable a field
  • Close opened window
  • Open Browser Window
  • Get Logged-in User ID
  • Attach Event to control
  • Set Description field in E-mail entity
  • Set IFrame URL
  • Get Schema Names of the Attributes
  • Get Teams of User
  • Filtered Lookup
  • Trigger the Workflow
  • Set field value using query string parameter
  • Change the Status and Status Reason of the record
  • Get the current form name
  • Refresh the form
  • Hide left navigation item
  • Set field requirement level in run time
  • Get Organization URL


PREVENT , STOP SAVE FORM OPERATION USING JAVASCRIPT IN MS CRM 2013 (prevent form from save ms crm)

WHEN YOU WANT TO ABORT AN SAVE OPERATION IN MS CRM , WE CAN USE THIS JAVASCRIPT TO STOP SAVE OPERATION IN MS CRM

   context.getEventArgs().preventDefault();

1. FIRST ADD A WEB-RESOURCE PASSING PARAMETER .

function checkbox(context) {

    var innerhtmls = Xrm.Page.ui.tabs.get("{cab6696b-b74a-47a4-b278-fc07fe780565}" ).sections.get( "Sec_IdProof").$1l_0.innerHTML;
    var checkedis = innerhtmls.match( /defaultvalue="1"/g );

Get all types of all input tags from a section using javascript in ms crm 2011, ms crm 2013 , ms crm 2015 ( no of checkbox checked in an section)

This is an Example for checking no of checkbox checked in an section not using jquery ( as jquery will not work in mobile version of ms crm)



function
 checkboxcheck() {   
    var innerhtmls = Xrm.Page.ui.tabs.get("tabname" ).sections.get( "Sectionname").$1l_0.innerHTML;
        // defaultvalue="1" = checked and defaultvalue="0" unchecked 
     var checkedis = innerhtmls.match( /defaultvalue="1"/g );

EMAIL , ZIPCODE , CONTACT NO VALIDATION USING JAVASCRIPT IN PORTAL / HTML

Java-Script Validation can be used in portal in html , php , java etc .


1. Email Validation : We have used an Regex here , and compared the text in input with it and given an alert.

    function validateemail() {
        var ccc = document.getElementById( 'idemailtb').value;
        var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
        if (!reg.test(ccc)) {
        alert( "Invalid Email Id");
          }
    }

SET AND GET VALUE FROM LOOKUP TO LOOKUP USING JAVASCRIPT IN MSCRM 2011 , 2013


function lookuptolookup() {
    //want the code to run only when some one update form click here to know about FORM TYPE
    var formtype = Xrm.Page.ui.getFormType();
    if (formtype == 2) {
        //look have the values " 1.id 2. name 3. entity type " so need to be in array
        var lookup = new Array();
        lookup = Xrm.Page.getAttribute( "new_test5_lookup" ).getValue();