Archive for the ‘Jscripts’ Category

getUserPrivilege

Returns an object with three Boolean properties corresponding to privileges indicating if the user can create, read or update data values for an attribute.

Xrm.Page.getAttribute("attributeschema").getUserPrivilege().canCreate
Xrm.Page.getAttribute("attributeschema").getUserPrivilege().canUpdate
Xrm.Page.getAttribute("attributeschema").getUserPrivilege().canRead

When retrieving records using OData in MS CRM 2011 the page size is fixed to Max 50 records. So in my example I’m going to push the first 50 records in an array and retrieve next page results using the URI (“__next”) provided in the JSON response object.

In my case i’m going to retrieve records in Account entity. Here is the code:

relatedAccounts = [];

function onload() {
    var serverUrl = Xrm.Page.context.getServerUrl();
    var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,Name,&$filter=StateCode/Value eq 0";
    GetRecords(oDataUri);
    var totalRecords = relatedAccounts.length;
}

function GetRecords(url) {
    jQuery.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: url,
        async: false,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (data && data.d != null && data.d.results != null) {
                AddRecordsToArray(data.d.results);
                FetchRecordsCallBack(data.d);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            alert("Error :  has occured during retrieval of the records ");
        }
    });
}

function AddRecordsToArray(records) {
    for (var i = 0; i < records.length; i++) {
        relatedAccounts.push(records[i]);
    }
}

function FetchRecordsCallBack(records) {
    if (records.__next != null) {
        var url = records.__next;
        GetRecords(url);
    }
}

urlrecords

TotalRecords

DetailedRecords

To add a jscript validation for Activate or Deactivate record in CRM, everyone might probably know that we can pass the execution context as the parameter and add the validation code as below:

function OnSave(context) {
    if (context != null && context.getEventArgs() != null) {
        var saveMode = context.getEventArgs().getSaveMode();
        if (saveMode == "5") {
            // Add Deactivate validation code here
            alert("Deactivate Event");
        }
        else if (saveMode == "6") {
            // Add Activate validation code here
            alert("Activate Event");
        }
    }
}

If you observe the above two pictures, the alert message is triggered after the OOB “Confirm Contact Deactivation” message from CRM.

In one of my requirement, i need to add jscript validation before I get the OOB Confirm deactivation message. So to achieve that, first we need to know what function is called on the “Deactivate” ribbon button in CRM.

In sdk folder you can get all the CRM ribbon xml files under sdk\resources\exportedribbonxml location. In my case i need contactribbon xml file. If you open that file using visual studio, we can get the function name of deactivate button in ribbon button Command.

The command name is “Mscrm.Form.Deactivate” and jscript function name is “changeState”

Now create a new solution and add the “contact” entity to edit the ribbon customization.

Export the solution and open the customization xml file. Go to <RibbonDiffXml> and Add the following code under <CommandDefinitions> (Copy the CommandDefinition from the sdk).

Replace the function name and Library as shown above with your own file and import the solution into CRM and publish it.

Before importing the solution make sure the function and library already exists.

You can add your business required validation and call the “changeState” function to trigger OOB Deactivate record. Below is the jscript code :

function DeactivateContact(btnType, typeCode, value) {
    if (Xrm.Page.getAttribute("parentcustomerid").getValue() == null) {
        alert("Please add parent customer");
        return false;
    }
    else {
        changeState(btnType, typeCode, value);
    }
}

From now your custom validation logic will trigger first and then you can call the OOB Deactivate function method (changeState) to show the confirm message as below.

In the same way you can add the custom logic for “Activate” or for any other ribbon button by copying the CommandDefinition from sdk

To Expand Tab

Xrm.Page.ui.tabs.get("<tabName>").setDisplayState("expanded");

To Collapse Tab

Xrm.Page.ui.tabs.get("<tabName>").setDisplayState("collapsed");

In the Phone Call entity there is a field called “Recipent” which is a datatype of PartyList. And by default it shows Account, Contact, Lead and User entities.

If you want to show only “Contacts” in the lookup, then you can add the following jscript code in your phone call entity “onload” event.

function OnLoad() {
    document.getElementById("to").setAttribute("defaulttype", "2");
    document.getElementById("to").setAttribute("lookuptypes", "2");
    document.getElementById("to").setAttribute("lookuptypeIcons", "/_imgs/ico_16_2.gif");
}

You can also achieve the same by using “crmForm.all” instead of “document.getElementById”

function OnLoad() {
    crmForm.all.to.setAttribute("defaulttype", "2");
    crmForm.all.to.setAttribute("lookuptypes", "2");
    crmForm.all.to.setAttribute("lookuptypeIcons", "/_imgs/ico_16_2.gif");
}

If you want to achieve using Jquery, then you can add the following code. Dont forget to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

function OnLoad() {
    $("#to").attr("defaulttype", "2");
    $("#to").attr("lookuptypes", "2");
    $("#to").attr("lookuptypeIcons", "/_imgs/ico_16_2.gif");
}

Filter 2 entities in the Recipent lookup

Now for example if you want to filter 2 entities in the Recipent lookup, you can add the following code on your onload event. Im using Account and Contact in my example.

function OnLoad() {
    document.getElementById("to").setAttribute("lookuptypenames", "contact:2:Contact,account:1:Account");
    document.getElementById("to").setAttribute("lookuptypes", "1,2");
    document.getElementById("to").setAttribute("lookuptypeIcons", "/_imgs/ico_16_2.gif:/_imgs/ico_16_1.gif");
}

You can also achieve the same by using “crmForm.all” instead of “document.getElementById”

function OnLoad() {
    crmForm.all.to.setAttribute("lookuptypenames", "contact:2:Contact,account:1:Account");
    crmForm.all.to.setAttribute("lookuptypes", "1,2");
    crmForm.all.to.setAttribute("lookuptypeIcons", "/_imgs/ico_16_2.gif:/_imgs/ico_16_1.gif");
}

If you want to achieve using Jquery, then you can add the following code. Dont forget to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

function OnLoad() {
    $("#to").attr("lookuptypenames", "contact:2:Contact,account:1:Account");
    $("#to").attr("lookuptypes", "1,2");
    $("#to").attr("lookuptypeIcons", "/_imgs/ico_16_2.gif:/_imgs/ico_16_1.gif");
}

Delete Account record using Jscript

In my example i’m going to Delete account entity record in CRM.

To perform an ODATA call, we need to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

function DeleteAccount() {
    // Pass the guid of the account.
    var accountId = '191E1ECD-500A-E211-B3FA-Q3E3B508F839';

    var serverUrl = Xrm.Page.context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/AccountSet";
    var ODataPath = serverUrl + ODATA_ENDPOINT;
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: ODataPath + "(guid'" + accountId + "')",
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
        }
    });
}

Update Account record using Jscript

In my example i’m going to Update account entity record in CRM.

To perform an ODATA call, we need to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

function UpdateAccount() {
    var accountId = Xrm.Page.data.entity.getId();

    var objAccount = new Object();
    // set the name of Account
    objAccount.Name = "Account Updated from jscript";

    // set the Primary Contact lookup field
    objAccount.PrimaryContactId = { Id: '{421E1EE5-500A-E211-B3FA-78E3B508F827}', LogicalName: "contact", Name: 'Adrian Dumitrascu (sample)' };

    // set the Address Type optionset field
    objAccount.Address1_AddressTypeCode = { Value: 2 };

    // set the Credit Hold boolean field
    objAccount.CreditOnHold = true;

    // Parse the entity object into JSON 
    var jsonEntity = window.JSON.stringify(objAccount);

    var serverUrl = Xrm.Page.context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/AccountSet";
    var ODataPath = serverUrl + ODATA_ENDPOINT;
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: ODataPath + "(guid'" + accountId + "')",
        data: jsonEntity,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
        }
    });
}

Add Account record using Jscript

In my example i’m going to create account entity record in CRM.

To perform an ODATA call, we need to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

function CreateAccount() {
    var serverUrl = Xrm.Page.context.getServerUrl().toString();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var ODATA_EntityCollection = "/AccountSet";

    var objAccount = new Object();
    // set the name of Account
    objAccount.Name = "Account created from jscript";

    // set the Primary Contact lookup field
    objAccount.PrimaryContactId = { Id: '{421E1EE5-500A-E211-B3FA-78E3B508F827}', LogicalName: "contact", Name: 'Adrian Dumitrascu (sample)' };

    // set the Address Type optionset field
    objAccount.Address1_AddressTypeCode = { Value: 2 };

    // set the Credit Hold boolean field
    objAccount.CreditOnHold = true;

    // Parse the entity object into JSON 
    var jsonEntity = window.JSON.stringify(objAccount);

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection,
        data: jsonEntity,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (response) {
            if (response != null && response.d != null) {
                alert(response.d.AccountId);
            }
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
        }
    });
}

To perform an ODATA call, we need to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

function DeleteNotes() {
    // Pass the guid of the annotation.
    var annotationId = 'C5E3D277-6510-E211-8C0E-78E3B511A681';

    var serverUrl = Xrm.Page.context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/AnnotationSet";
    var ODataPath = serverUrl + ODATA_ENDPOINT;
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: ODataPath + "(guid'" + annotationId + "')",
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
        }
    });
}

Update Note using Jscript

In my example i’m going to update notetext and note subject in CRM.

To perform an ODATA call, we need to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

function UpdateNotes() {
    // create notes object
    var objNotes = new Object();
    objNotes.Subject = "Note Subject Updated";
    objNotes.NoteText = "First Note Updated";

    // Pass the guid of the annotation.
    var annotationId = 'A1A04803-6310-E211-8C0E-78E3B511A681';
    var jsonEntity = window.JSON.stringify(objNotes);

    var serverUrl = Xrm.Page.context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/AnnotationSet";
    var ODataPath = serverUrl + ODATA_ENDPOINT;
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: ODataPath + "(guid'" + annotationId + "')",
        data: jsonEntity,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
        }
    });
}