RSS

Monthly Archives: January 2014

CRM 2013 Multi Pick List

Background

In One of our previous Blogs CRM 2011 Multi Pick list, we have discussed about creating Multiple Pick List in the MS Dynamic CRM form. But the previous post was for CRM 2011. As the CRM 2013 is supported across different browsers, we have to change a little in the code to make it compatible for all major browsers. Here is the modified Blog for Multi Pick List in MS Dynamics CRM 2013.

Let’s start

In this article, we will create a Multiple Pick List for Dynamic CRM form. User can enter multiple data from Pick List by CheckBox. This will also work on all the four major browsers (IE, Firefox, Chrome and Safari).
5-1-2013 1-35-04 PM

Requirement

There was a requirement in a project, where user wanted to select, not only one, but also multiple value from a Pick List.

Solution

Steps which are needed to be followed:-

  1. Creation of Field.
  2. Create Web Resource.
  3. Add function to the form.

Creation of Field

There are two fields which are created on the entity you want to make Multi Pick List :-

  1. OptionSet Field :- all the option which must be entered
  2. Data Field:- Multiple Lines of Text Field. In which data is stored.

Include both the field on the form.

Create Web Resource

Create a Web Resource with the following code:-

// var_sc_optionset >>  Provide logical-name for Option Set field
// var_sc_optionsetvalue >> Provide logical-name for field which will
//                          store the multi selected values for Option Set
// OS >> Provide Options of the Optionset field
//       (Ex:- Xrm.Page.getAttribute("Option Set field logical-name").getOptions())
// OSV >> Provide text field object which will store the
//        multi selected values for Option Set
//       (Ex:- document.getElementById("text field logical-name"))

// Method to convert an optionset to multi select OptionSet
function ConvertToMultiSelect(var_sc_optionset, var_sc_optionsetvalue, OS, OSV) {

    if (OS != null && OSV != null) {

        document.getElementById(var_sc_optionset).style.display = "none";

        // Create a DIV container
        var addDiv = document.createElement("div");
        addDiv.id = var_sc_optionsetvalue + "_m";
        addDiv.style.width = "100%";
        addDiv.style.height = "80px";
        addDiv.style.background = "#ffffff";
        addDiv.style.color = "white";
        addDiv.style.overflow = "auto";
        addDiv.style.border = "1px #6699cc solid";
        document.getElementById(var_sc_optionset).parentNode.appendChild(addDiv);

        // Declaration of variables will be used in the loop depending upon the browser
        var initialValue = 0;
        var maxValue = 0;

        var nAgt = navigator.userAgent;

        if (nAgt.indexOf("Firefox") != -1) {  // If the broswer is "Firefox" 

            initialValue = 1;
            maxValue = OS.length;

        }
        else if (nAgt.indexOf("Chrome") != -1 || nAgt.indexOf("IE") != -1) { // If the browser is Chrome or IE

            initialValue = 0;
            maxValue = OS.length - 1;
        }
        else if (nAgt.indexOf("Safari") != -1) {  // If the browser id "Safari"

            initialValue = 1;
            maxValue = OS.length;
        }

        // Initialise checkbox controls
        for (var i = initialValue; i < maxValue; i++) {
            var pOption = OS[i];
            if (!IsChecked(pOption.value, var_sc_optionsetvalue)) {
                var addInput = document.createElement("input");
                addInput.type = "checkbox";
                addInput.style.border = "none";
                addInput.style.width = "25px";
                addInput.style.align = "left";
                addInput.style.color = "#000000";
                addInput.onclick = function () {

                    OnSave(var_sc_optionset, var_sc_optionsetvalue);
                    createTable(var_sc_optionsetvalue);
                }
            }
            else {

                var addInput = document.createElement("input");
                addInput.type = "checkbox";
                addInput.checked = true;
                addInput.setAttribute("checked", true);
                addInput.checked = "checked";
                addInput.defaultChecked = true;
                addInput.style.border = "none";
                addInput.style.width = "25px";
                addInput.style.align = "left";
                addInput.style.color = "#000000";
                addInput.onclick = function () {

                    OnSave(var_sc_optionset, var_sc_optionsetvalue);
                    createTable(var_sc_optionsetvalue);
                }

            }

            //Create Label
            var addLabel = document.createElement("label");
            addLabel.style.color = "#000000";
            addLabel.innerHTML = pOption.text;

            var addBr = document.createElement("br"); // it's a 'br' flag

            document.getElementById(var_sc_optionset).nextSibling.appendChild(addInput);
            document.getElementById(var_sc_optionset).nextSibling.appendChild(addLabel);
            document.getElementById(var_sc_optionset).nextSibling.appendChild(addBr);
        }
    }
}

// Check if it is selected
function IsChecked(pText, optionSetValue) {

    var selectedValue = Xrm.Page.getAttribute(optionSetValue).getValue();

    if (selectedValue != "" && selectedValue != null) {
        var OSVT = selectedValue.split(",");

        for (var i = 0; i < OSVT.length; i++) {
            if (OSVT[i] == pText)
                return true;
        }
    }

    return false;
}

// var_sc_optionsetvalue >> Provide logical-name for field which will
//                          store the multi selected values for Option Set
// optionSet>> Provide logical-name of Option Set field 
function OnSave(optionSet, var_sc_optionsetvalue) {

    var OS = document.getElementById(optionSet);
    var options = Xrm.Page.getAttribute(optionSet).getOptions();
    var getInput = OS.nextSibling.getElementsByTagName("input");
    var result = "";
    var result1 = "";
    var nAgt = navigator.userAgent;

    for (var i = 0; i < getInput.length; i++) {
        if (getInput[i].checked) {
            result += getInput[i].nextSibling.innerHTML + ",";

            if (nAgt.indexOf("Firefox") != -1) {  //If the broswer is "Firefox"
                result1 += options[i + 1].value + ",";
            }

            else if (nAgt.indexOf("Chrome") != -1 || nAgt.indexOf("IE") != -1) { //If the browser is Chrome or IE

                result1 += options[i].value + ",";
            }

            else if (nAgt.indexOf("Safari") != -1) {  //If the browser id "Safari"

                result1 += options[i + 1].value + ",";

            }

        }
    }

    //save value
    Xrm.Page.getAttribute(var_sc_optionsetvalue).setValue(result1);
}

// var_sc_optionsetvalue >> Provide logical-name for field which will
//                          store the multi selected values for Option Set
function createTable(var_sc_optionsetvalue) {
    // Get OptionSet value
    var OptionValue = Xrm.Page.getAttribute(var_sc_optionsetvalue);
    var c_OptionValue = Xrm.Page.getControl(var_sc_optionsetvalue);
    var d_OptionValue = var_sc_optionsetvalue + "_d";

    if (OptionValue.getValue() != null) {

        var OptionValueHtml = "<div style=\"overflow-y:auto;width:100%;display: none; min-height: 5em; max-height: 1000px;\">";

        OptionValueHtml += "<table style='width:100%;height: 100%;'>";
        var OptionValueV = OptionValue.getValue();

        var OptionValueT = OptionValueV.split(",");
        var cols = 0;
        for (var row = 0; row < OptionValueT.length - 1; row++) {
            OptionValueHtml += "<tr  style='height:20px;'>";
            for (var i = cols; i < cols + 3; i++) {
                OptionValueHtml += "<td style='width:33%;'>";
                if (OptionValueT[i] != null || OptionValueT[i] != undefined) {

                    OptionValueHtml += OptionValueT[i];
                }
                OptionValueHtml += "</td>";
            }
            cols = cols + 3;
            OptionValueHtml += "</tr>";
            if (cols >= OptionValueT.length) {
                break;
            }
        }

        OptionValueHtml += "</table>";
        OptionValueHtml += "</div>";
        document.getElementById(d_OptionValue).innerHTML = OptionValueHtml;
    }  
}

Add function to the form

There are three functions need to be added

  • On Load :-

    1. Function name :- ConvertToMultiSelect.
      Parameter :- “new_multipicklistoption”, “new_multipicklistvalue”, Xrm.Page.getAttribute(“new_multipicklistoption”).getOptions(), document.getElementById(“new_multipicklistvalue”)
    2. Function name :- createTable
      Parameter :- “new_multipicklistvalue”.

5-1-2013 1-11-58 PM

  • On Save :-

    1. Function Name :- OnSave
      Parameter :- “new_multipicklistoption”, “new_multipicklistvalue”

5-1-2013 1-12-52 PM

Reference

CRM 2011 Multi Pick list

By Ranjan Parhi
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

Advertisements
 
2 Comments

Posted by on January 30, 2014 in WebResources

 

Tags: , , , , , , , , , , , , , , , , , , , , , ,

How to append Email Template to Email Entity Form on Load through JavaScript

Introduction

Generally, we add a Signature at the bottom of Email before we send. One of my projects needed the same requirement. We need to insert one Signature Email Template into the description body of Email Form on form load. I have found a solution and now I am going to describe it.

Steps

  1. Create a web resource of Script type and add to the Email Form library
  2. Add the “AddSignatureToEmail” function to the form “onload” event
  3. Create a Email Template containing Signature body and copy the Template Id
  4. Replace that Template Id in the following code for variable “emailTemplateToLoad

Code

Following is the Code snippet.

function AddSignatureToEmail() {
	// Check the form type should be 'create' type
	if (Xrm.Page.ui.getFormType() != 1) { return; }

	// Pre-fill a template signature
	var drawSignature = false;
	var emailTemplateToLoad = "b348fc8b-1e6e-e311-9d64-6c3be5a86df8 "; //created email template Id

	// Check if description is blank or similar
	var theDescription = Xrm.Page.getAttribute("description").getValue();
	if (theDescription == null) {
		drawSignature = true;
	} else if (theDescription == undefined) {
		drawSignature = true;
	} else if (stripHTML(theDescription) == "") {
		drawSignature = true;
	} else if (stripHTML(theDescription).length < 10) {
		drawSignature = true;
	}

	if (drawSignature) {
		// Get Regarding object details
		var regardingobjectid = Xrm.Page.getAttribute("regardingobjectid");
		if (regardingobjectid==undefined) { return; }
		var RegardingItems = Xrm.Page.getAttribute("regardingobjectid").getValue();

		// The signature will not append if regarding field remains blank.
		if (RegardingItems!=null) {
			var regardingObjectId = RegardingItems[0].id;
			var regardingObjectType = RegardingItems[0].type;

			if (regardingObjectId == null || regardingObjectId == "") { return; }
			if (regardingObjectType == null || regardingObjectType == "") { return; }

			// Retrieving email template details

			var command = new RemoteCommand("EmailTemplateService", "GetInstantiatedEmailTemplate");
			command.SetParameter("templateId", emailTemplateToLoad);
			command.SetParameter("objectId", regardingObjectId);
			command.SetParameter("objectTypeCode", regardingObjectType);
			var result = command.Execute();

			if (result.Success) {
				var o = new Object();
				o.EmailBody = "";
				o.EmailSubject = "";
				if (typeof (result.ReturnValue) == "string") {
					// Create a Xml Document of the return value to retrieve actual data
					oXml = CreateXmlDocument(result.ReturnValue);
					o.EmailBody = oXml.lastChild.lastElementChild.textContent;

					Xrm.Page.getAttribute("description").setValue(o.EmailBody);
				}
			}
		}	
	}
}

function stripHTML(signature) {
	var tmp = document.createElement("DIV");
	tmp.innerHTML = signature;
	return tmp.textContent || tmp.innerText;
}

function CreateXmlDocument(signatureXmlStr) {
    // Function to create Xml formate of return email template data
	var parseXml;

	if (window.DOMParser) {
		parseXml = function (xmlStr) {
			return (new window.DOMParser()).parseFromString(xmlStr, "text/xml");
		};
	}
	else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
		parseXml = function (xmlStr) {	
			var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async = "false";
			xmlDoc.loadXML(xmlStr);
			
			return xmlDoc;
		};
	} 
	else {
		parseXml = function () { return null; }
	}

	var xml = parseXml(signatureXmlStr);
	if (xml) {
		return xml;
	}
}

var a = window.setTimeout(AddSignatureToEmail, 1500);

By Sukanta Mangal
Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 
3 Comments

Posted by on January 13, 2014 in WebResources

 

Tags: , , , , , , , , , , , , , , , , , ,

How to Create Records through Dialog Process and do fields mapping with the Parent Record

Introduction

As we know, in MS CRM, we always try to find solution of any requirement through Out Of The Box. It doesn’t mean that, we can’t do it by writing code. But Out of The Box gives better performance. So, let’s discuss how to create records through Dialog Process and do fields mapping with the Parent Record.

Background

According to one of my project requirement, we had to create new record(s) on custom button click, from one existing record and that will be done only through Dialog Process. Before record create, in background, some of data from parent record should automatically get populated to new record’s fields (i.e. Fields mapping). I have found a solution by doing some research.

Steps

Let’s explore step by step.

Here I will open Dialog Process from existing Contact record and create Contact and Opportunity records through dialog sequentially.

Step 1: Create a Process of Dialog Category

Create Dialog Process

Step 2: Add a step of “Page” and under which add “Prompt and Response” step, then click “Set properties” to to create control for record inside dialog

See the following picture.
Add Step Page

Step 3: Mapping Dialog Fields with Contact Fields

After creating all fields required, add a step of “Create record” from Add Steps DropDown. Then choose the record type and click “Set Properties“. Here we will be able to do fields mapping using both Parent data and Dialog Fields data.
The Red colored box on the right side is showing all fields contains in Dialog. Map those fields with corresponding fields in Contact.
Mapping Dialog Fields with Contact Fields

Step 4: Populating Parent Fields data to New Record

The Red Colored box showing fields mapping between Parent record and New record. Same way choose any field and map that with field of Contact
Populating Parent Fields data to new record

Step 5: To set Parent record with one Lookup field of new record

Follow the below Picture.
Set Parent record with Lookup field of new record

Step 6: To add a created record’s link in the end of Dialog

Add a new page and again add a step of “Prompt and Response” under it. Then click Set properties and follow the below image. After that activate the Dialog Process.
Add created record link in the end of Dialog

Step 7: Script to open created Dialog on Button Click

  • Copy the Id of the new Dialog Process from location bar and then do the following
  • Create a Web Resource of Script type using below script
  • Add the Web Resource to the Button Click Event
function LaunchModalDialog()
{
    var dialogId = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"; //id of dialog process
    var recordId = Xrm.Page.data.entity.getId();
    var typeName = Xrm.Page.data.entity.getEntityName();
    recordId = recordId.toString();
    recordId = recordId.replace("{", "");
    recordId = recordId.replace("}", "");

    var serverUrl = Xrm.page.getServerUrl();
    
    // Load modal
    var serverUri = serverUrl +'/cs/dialog/rundialog.aspx';

    var mypath = serverUri +'?DialogId=%7b' + dialogId.toUpperCase() +'%7d&EntityName=' + typeName + '&ObjectId=%7b' + recordId +'%7d';

    // First item from selected contacts only
    window.showModalDialog(mypath);

    // Reload form.
    window.location.reload(true);
}

By Sukanta Mangal
Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 
 

Tags: , , , , , , , , , , , , , , , ,

 
%d bloggers like this: