Status Change using WebApi

In Dynamics 365, OOTB status field value can be changed in many different ways.

Following WebApi can be used to update the Status (statecode + statuscode) as follows.

changeStatus = function (executionContext, entityLogicalName, recordId, statecode, statuscode) {
// Remove brackets from the GUID if there’s any
var id = recordId.replace(“{“, “”).replace(“}”, “”);
// Set statecode and statuscode
var data = {
“statecode”: statecode,
“statuscode”: statuscode
};
// WebApi call
Xrm.WebApi.updateRecord(entityLogicalName, id, data).then(function  success(result) {
executionContext.getFormContext().data.refresh(true);
}, function (error) {
executionContext.getFormContext().data.refresh(true);
});
};

Xrm.Utility : openEntityForm with Parameters

Using “openEntityForm” a CRM form can be opened. While it is opening, different form fields values can be populated and those values can be passed to the form.
Xrm.Utility.openEntityForm(name,id,parameters,windowOptions)
name: Entity Logical Name
id: Record id
parameters: Form id, Field Ids, and Values, Custom query string parameters
windowOptions: Flag to open as a New Window

Passing Parameters and Populate Field Values in a New Contact Form

function openNewContact() {
var caseId = Xrm.Page.data.entity.getId();
var title = Xrm.Page.getAttribute(“title”).getValue();
    var windowOptions = {
openInNewWindow: true
};
var parameters = {};
parameters[“new_caseid”] = caseId;
parameters[“new_caseidname”] = title;
Xrm.Utility.openEntityForm(“contact”, null, parameters, windowOptions);
}

Continue reading “Xrm.Utility : openEntityForm with Parameters”

Layered Multi Select Checkboxes – Custom Controls in CRM – Part 2

Layered multi level checkboxes challenge can be acheived by using CRM Optionset control and javascripts too. However there is a technique to be used to identify parent and child levels of the multi layered checkboxes. Each picklist item’s value can be used to decide the layer of the checkbox.

Control looks like this in the CRM form after implementing it.

Follow the steps below to work with Layered Multi Select Checkbox control.
Continue reading “Layered Multi Select Checkboxes – Custom Controls in CRM – Part 2”

Multi Select Checkboxes – Custom Controls in CRM – Part 1

Multi select check boxes control is a very essential control in web forms. Some times client needs exactly the same feature in CRM forms as well. When the requirement is to develop a dynamic multi select checkboxes control its really difficult for the developer to implement the feature in CRM. CRM developers will have a little relief with this solution even if there are Javascripts needed to activate the functionalities.

An Option Set control and a Multi line textbox are used to create the Multi Select Checkboxes control. Labels of the checkboxes can be stored in the optionset control as items. Selected values will be saved in the multi line textbox seperated by semi colons.

Control looks like this in the CRM form after implementing it.

Multi select checkbox control in the form

Follow the steps below to work with Multi Select Checkbox control.

Continue reading “Multi Select Checkboxes – Custom Controls in CRM – Part 1”

Disable Required Fileds When Hide Tabs in CRM 2011

There are requirements to hide tabs according to the selections in the form and if any tab contains required fields it will display them automatically and asking user to fill those fields when saving the form.

Following Javascript function will disalbe all the controls in the tab and then it will not ask user to fill those required fields.

// tabName : Name of the Tab, isDisable: booloean value for Enable/Disable controls
DisableAllControlsInTab: function (tabName, isDisable) {
    var tabControl = Xrm.Page.ui.tabs.get(tabName);
    if (tabControl != null) {
        Xrm.Page.ui.controls.forEach(
        function (control, index) {
            if (control.getParent().getParent() == tabControl && control.getControlType() != "subgrid") {
                control.setDisabled(isDisable);
            }
        });
    }
}

Following Javascript function can be used to show or hide the tab and it will disable/enable its controls accordingly.
Continue reading “Disable Required Fileds When Hide Tabs in CRM 2011”

Intellisense for Xrm.Page in CRM 2011

In CRM 2011 javascripts for crm forms can be stored externally as web resources and those are no longer embedded in CRM forms. Javascripts in web resources can be edited using an external editor. Visual Studio IDE provides intellisense to the Javascripts in Xrm.Page with the help of XrmPage-vsdoc.js. It works with Visual Studio 2010 and Visual Studio 2012. Thanks to Patrick Verbeeten for bringing this cool feature in.

In order to get the intellisense Visual Studio IDE needs the reference of the XrmPage-vsdoc.js file. Follow the following steps to enable intellisense for Xrm.Page in the Javascript.

[1] Download XrmPage-vsdoc.js from HERE

[2] Add XrmPage-vsdoc.js in to the Visual Studio IDE

Continue reading “Intellisense for Xrm.Page in CRM 2011”

Set Server Url to OData Query Dynamically using JavaScripts in CRM 2011 Forms

Following statement can be used to retrieve accounts from the CRM application with the MyOrganization hosted in DevServer.

http://DevServer/MyOrganisation/xrmservices/2011/OrganizationData.svc/AccountSet?$select=swmship_FirstName,swmship_Surname&$filter=startswith(Address1_City,’Ca’)

http://DevServer/MyOrganisation/” part is varried according to the hosted server and the organization and it might raise errors when the above OData query get executed in some other CRM application.

Following JavaScript can be used to get the server url in the CRM 2011 forms.

var serverUrl = Xrm.Page.context.getServerUrl();

Get the next part of the OData service part.

var GlobalODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc/";

Continue reading “Set Server Url to OData Query Dynamically using JavaScripts in CRM 2011 Forms”

Useful Javascripts for CRM 2011


// Get the form type
GetFormType: function () {
 var FORM_TYPE_CREATE = 1;
 var FORM_TYPE_UPDATE = 2;
 var FORM_TYPE_READ_ONLY = 3;
 var FORM_TYPE_DISABLED = 4;
 var FORM_TYPE_QUICK_CREATE = 5;
 var FORM_TYPE_BULK_EDIT = 6;

 var formType = Xrm.Page.ui.getFormType();
 if (formType == FORM_TYPE_CREATE) {
  alert("This record has not yet been created.");
 }
 else {
  alert("This record exists in the database.");
 }
}




// Registering an event for a custom control, and call a method when it fires
RegisterEventForACustomControl: function (var controlId) {
        var customField = document.getElementById(controlId);
        /* Build Toggle Function */
        var f = "var ef=function() { " +
                  "MethodToBeCalled();" +
                  " };";
        eval(f);
        /* Attach to click event */
        customField.attachEvent('onclick', ef, false);
}

MethodToBeCalled: function () {
        // Do something
}




// Disable/Enable all controls in a Tab
DisableAllControlsInTab: function (tabName, isDisable) {
    var tabControl = Xrm.Page.ui.tabs.get(tabName);
    if (tabControl != null) {
        Xrm.Page.ui.controls.forEach(
        function (control, index) {
            if (control.getParent().getParent() == tabControl && control.getControlType() != "subgrid") {
                control.setDisabled(isDisable);
            }
        });
    }
}




// Get the value from a CRM field
var varMyValue = Xrm.Page.getAttribute("CRMFieldSchemaName”).getValue() ;

// Set the value of a CRM field
Xrm.Page.getAttribute("CRMFieldSchemaName”).setValue(‘New Value’);




// Hide/Show a tab using 
Xrm.Page.ui.tabs.get("CRMTabName").setVisible(true);
Xrm.Page.ui.tabs.get("CRMTabName").setVisible(false);

Xrm.Page.ui.tabs.get(5).SetVisible(false);
Xrm.Page.ui.tabs.get(5).SetVisible(true);




// Hide/Show a section in a tab
Xrm.Page.ui.tabs.get("CrmTabName").sections.get("SectionName").setVisible(true);
Xrm.Page.ui.tabs.get("CrmTabName").sections.get("SectionName").setVisible(false);




// Call the onchange event of a field
Xrm.Page.getAttribute("CRMFieldSchemaName”).fireOnChange();




// Get the selected value of picklist
Xrm.Page.getAttribute("CRMFieldSchemaName”).getSelectedOption().getValue();




// Set the requirement level
Xrm.Page.getAttribute("CRMFieldSchemaName”).setRequiredLevel("none”);
Xrm.Page.getAttribute("CRMFieldSchemaName”).setRequiredLevel("required”);
Xrm.Page.getAttribute("CRMFieldSchemaName”).setRequiredLevel("recommended”);




// Set the focus to a field
Xrm.Page.getControl("CRMFieldSchemaName”).setFocus(true);




// Return array of strings of users security role GUIDs:
Xrm.Page.context.getUserRoles()




// Setting Force Submit to the field, This must be set to save the data
Xrm.Page.getAttribute("CRMFieldSchemaName”).setSubmitMode("always”);




// Stop an on save event
event.returnValue = false;




// Form close
Xrm.Page.ui.close();


Adding a custom button to CRM 2011 Form

Adding a button to a CRM Form is quite challenging as we don’t have any IDE to design it. But still it’s possible using JavaScript.
Here’s the JavaScript code for that.
// Create the button, using the new_custombutton field as a container
        CreateButtonCRM5(‘swpmt_cancelddi’, ‘Cancel DDI’, ’75 px’, ’16_cancel.png’, CustomClickFunction);


// Custom Function
function CustomClickFunction() {
    var response = confirm(“DDI Status is to be changed to ‘Cancelling’. Do you want to continue?”);
    if (response) {
        Xrm.Page.getAttribute(‘swpmt_ddistatus’).setValue(4);
    }
}


// Add a button to the CRM Form – Begin


// CODE
// Create Dynamic Button for CRM 2011
function removeChildNodes(ctrl) {
    while (ctrl.childNodes[0]) {
        ctrl.removeChild(ctrl.childNodes[0]);
    }
}


function CreateButtonCRM5(fieldName, buttonText, buttonWidth, iconName, clickEvent) {
    functiontocall = clickEvent;
    crmForm.all.item(fieldName + “_c”).style.display = “none”;


    var li = document.createElement(“LI”);
    li.setAttribute(‘id’, fieldName + ‘LI’);
    li.setAttribute(‘className’, ‘ms-crm-Menu’);
    li.setAttribute(‘title’, buttonText);
    li.setAttribute(‘onclick’, functiontocall);
    li.setAttribute(‘onmousedown’, push_custom_button);
    li.setAttribute(‘onmouseup’, release_custom_button);
    li.style.width = buttonWidth;
    li.style.cursor = “hand”;
    li.style.textAlign = “center”;
    li.style.overflow = “hidden”;


    var span = document.createElement(“span”);
    span.setAttribute(‘className’, ‘ms-crm-Menu-Label’);
    span.setAttribute(‘id’, fieldName + ‘Span’);
    span.style.cursor = “hand”;
    li.appendChild(span);
    li.onmouseover = function () { span.setAttribute(‘className’, ‘ms-crm-Menu-Label-Hovered’); }
    li.onmouseout = function () { span.setAttribute(‘className’, ‘ms-crm-Menu-Label’); }


    var a = document.createElement(“a”);
    a.setAttribute(‘id’, fieldName + ‘A’);
    a.setAttribute(‘className’, ‘ms-crm-Menu-Label’);
    a.onclick = function () { return false; }
    a.setAttribute(‘target’, ‘_self’);
    a.setAttribute(‘href’, ‘javascript:onclick();’);
    a.style.cursor = “hand”;
    span.appendChild(a);


    var img = document.createElement(“img”);
    img.setAttribute(‘id’, fieldName + ‘Img’);
    img.setAttribute(‘className’, ‘ms-crm-Menu-ButtonFirst’);
    img.setAttribute(‘src’, ‘/_imgs/ico/’ + iconName);
    img.style.cursor = “hand”;


    var span2 = document.createElement(“span”);
    span2.setAttribute(‘id’, fieldName + ‘Span2’);
    span2.setAttribute(‘className’, ‘ms-crm-MenuItem-TextRTL’);
    span2.innerText = buttonText;
    span2.style.cursor = “hand”;
    a.appendChild(img);
    a.appendChild(span2);


    removeChildNodes(crmForm.all.item(fieldName + “_d”));
    crmForm.all.item(fieldName + “_d”).appendChild(li);
}


function push_custom_button() {
    window.event.srcElement.style.marginLeft = “1px”;
    window.event.srcElement.style.marginTop = “1px”;
}


function release_custom_button() {
    window.event.srcElement.style.marginLeft = “0px”;
    window.event.srcElement.style.marginTop = “0px”;
}


// Add a button to the CRM Form – End