Wednesday, 30 January 2013

Count Sub-grid records in entity in CRM 2011 using javascript



function requisitionproducts() {
//Get Current record Id
    var Guid = Xrm.Page.data.entity.getId();
    var fetchXml =
    "<fetch mapping='logical'>" +
       "<entity name='quotedetail'>" + //SubGrid entity name
    //Condition to Check the subGrid record is associated with current record      
          "<filter>" +  
             "<condition attribute='quoteid' operator='eq' value='" + Guid + "' />" +
          "</filter>" +
       "</entity>" +
    "</fetch>";
   
    var fetchedRecord = XrmServiceToolkit.Soap.Fetch(fetchXml)
    if (fetchedRecord.length > 0) {
        return true;
    }
}


After adding this web-resource you need to add the following files to your form page Libraries:

  1. Json
  2. jquery
  3. xrmservicetoolkit


Monday, 21 January 2013

Get Current user business unit in CRM 2011 using javascript


function GetBusinessUnit() {  
        var request = "<request i:type='b:WhoAmIRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
                            "<a:Parameters xmlns:c='http://schemas.datacontract.org/2004/07/System.Collections.Generic' />" +
                            "<a:RequestId i:nil='true' />" +
                            "<a:RequestName>WhoAmI</a:RequestName>" +
                          "</request>";
        var resultXml = XrmServiceToolkit.Soap.Execute(request);
        var buid = resultXml.getElementsByTagName("a:Results")[0].childNodes[1].childNodes[1].text;
        var cols = ["name"];
        var retrievedContact = XrmServiceToolkit.Soap.Retrieve("businessunit", buid, cols);
        var businessUnitName = retrievedContact.attributes['name'].value;
       alert(businessUnitName);
    }
After that you need to add the following files to the Form Libraries.

  1. Jquery
  2. Json2
  3. XrmServiceToolkit
Download these files from the following link: XrmServiceToolkit

Get Partylist/Lookup field id in CRM 2011 using Javascript


var lookup = new Array();
        lookup = Xrm.Page.getAttribute("to").getValue();
        for (var indxAttendees = 0; indxAttendees < lookup.length; indxAttendees++) {
        var lookupId = lookup[indxAttendees].id;
        var lookupName=lookup[indxAttendees].name;
        var lookupType=lookup[indxAttendees].entityType;
}

Tuesday, 8 January 2013

Hide section/field based on related entity/records in CRM 2011 using javascript


function retrieveworkorder() {

    var ordernumber = Xrm.Page.data.entity.getId();
    if (ordernumber != null) {
        var fetchXml =
                    "<fetch mapping='logical'>" +
                       "<entity name='jmh_workorder'>" +
                          "<attribute name='jmh_workordernumber' />" +
                          "<filter>" +
                             "<condition attribute='jmh_bespokeorderid' operator='eq' value='" + ordernumber + "' />" +
                          "</filter>" +
                       "</entity>" +
                    "</fetch>";

        var retrievedOrder = XrmServiceToolkit.Soap.Fetch(fetchXml);
//        alert(retrievedOrder.length);
        if (retrievedOrder.length > 0) {
            Xrm.Page.ui.tabs.get("general").sections.get("workorder").setVisible(false);
        }
    }

}

Reference: http://xrmservicetoolkit.codeplex.com/wikipage?title=Soap%20Functions 

Monday, 7 January 2013

Get Business Unit in CRM 2011 using javascript

  • Add the following script to your web resources:
function GetBusinessUnit() {
    var currentstore = Xrm.Page.getAttribute('jmh_store').getValue();
    if (currentstore == null) {
        var request = "<request i:type='b:WhoAmIRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
                            "<a:Parameters xmlns:c='http://schemas.datacontract.org/2004/07/System.Collections.Generic' />" +
                            "<a:RequestId i:nil='true' />" +
                            "<a:RequestName>WhoAmI</a:RequestName>" +
                          "</request>";
        var resultXml = XrmServiceToolkit.Soap.Execute(request);
        var buid = resultXml.getElementsByTagName("a:Results")[0].childNodes[1].childNodes[1].text;
        var cols = ["name"];
        var retrievedContact = XrmServiceToolkit.Soap.Retrieve("businessunit", buid, cols);
        var buName = retrievedContact.attributes['name'].value;
        SetLookupValue('jmh_store', buid, buName, 'businessunit');
    }

    function SetLookupValue(fieldName, id, name, entityType) {
        if (fieldName != null) {
            var lookupValue = new Array();
            lookupValue[0] = new Object();
            lookupValue[0].id = id;
            lookupValue[0].name = name;
            lookupValue[0].entityType = entityType;
            Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
        }
    }
}


Note : Add XrmServiceToolkit in the page library
Reference: http://xrmservicetoolkit.codeplex.com/wikipage?title=Soap%20Functions

Tuesday, 18 December 2012

Multi-selection options sets supports in all browser in CRM 2011 using javascript

This code will Support on IE, Chrome and FireFox....
Create Option set field which you want to convert to multi-select options.

Create Option set field
Create a Multiple lines of text field. This field only hold the user select values. So it would be invisible.

Multi line text field
After creating the above field that should be added to your form. The text field visibility mode should be invisible.

Then you need to create a new webresource file with the following code:

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

if (OS != null && OSV != null) {
        OS.style.display = "none";
        Xrm.Page.getControl(var_sc_optionsetvalue).setVisible(false);

        // Create a DIV container        
        var addDiv = null;
        var addInput = null;
        if (window.DOMParser) { //Chrome, Firefox and other browser
            try {                
                addDiv = document.createElement("div");
                addDiv.setAttribute("style", "overflow-y:auto; height:80px; border:1px #6699cc solid; background-color:#ffffff;");
            }
            catch (e) {
                alert(e);
            }
            OS.parentNode.appendChild(addDiv);

            // Initialise checkbox controls
            for (var i = 1; i < OS.options.length; i++) {

                var pOption = OS.options[i];
                if (!IsChecked(pOption.text, OS, OSV)) {                    
                    addInput = document.createElement("input");
                    addInput.setAttribute("type", "checkbox");
                    addInput.setAttribute("style", "border:none; width:25px; align:left;");
                } else {                   
                    addInput = document.createElement("input");
                    addInput.setAttribute("type", "checkbox");
                    addInput.setAttribute("checked", "checked");
                    addInput.setAttribute("style", "border:none; width:25px; align:left;");
                }

                var addLabel = document.createElement("label"); //("<label />");
                addLabel.innerText = pOption.text;

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

                OS.nextSibling.appendChild(addInput);
                OS.nextSibling.appendChild(addLabel);
                OS.nextSibling.appendChild(addBr);
            }
        }
        else {  //IE Support
            try {
                var addDiv = document.createElement("<div style='overflow-y:auto; height:80px; border:1px #6699cc solid; background-color:#ffffff;' />");                
            }
            catch (e) {
                alert(e);
            }
            OS.parentNode.appendChild(addDiv);

            // Initialise checkbox controls
            for (var i = 1; i < OS.options.length; i++) {

                var pOption = OS.options[i];
                if (!IsChecked(pOption.text, OS, OSV)) {
                                    var addInput = document.createElement("<input type='checkbox' style='border:none; width:25px; align:left;' />");
                    
                } else {
                                    var addInput = document.createElement("<input type='checkbox' checked='checked' style='border:none; width:25px; align:left;' />");                    
                }

                var addLabel = document.createElement("<label />");
                addLabel.innerText = pOption.text;

                var addBr = document.createElement("<br/>");           

                OS.nextSibling.appendChild(addInput);
                OS.nextSibling.appendChild(addLabel);
                OS.nextSibling.appendChild(addBr);
            }
        }
    }
}



  // Check if it is selected
  function IsChecked( pText , OS, OSV)
  {
    if(OSV.value != "")
    {
      var OSVT = OSV.value.split(";");
      for( var i = 0; i < OSVT.length; i++ )
      {
        if( OSVT[i] == pText )
          return true;
      }
    }
    return false;
  }
  
  // Save the selected text, this field can also be used in Advanced Find
  function OnSave(OS, var_sc_optionsetvalue)
  {
    var getInput = OS.nextSibling.getElementsByTagName("input");
    var result = '';

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

    //save value
    control = Xrm.Page.getControl(var_sc_optionsetvalue);
    attribute = control.getAttribute();
    attribute.setValue(result);

  }


After adding the file to webresource you need to add on form OnLoad and OnSave event.



Then pass the parameter on OnLoad event:

OnLoad function

OnSave event:

OnSave Event parameters
After reload your form it will be displayed like this


Set lookup field while calling a Entity/Activity from ribbon button in CRM 2011


Here the look-up field is set based on another look-up field in the target entity.

function setLookupfield() {
        if (Xrm.Page.data.entity.attributes.get('targetfieldName').getValue()==null) {
            var EntityName, EntityId, LookupFieldObject;
            var Name = "";
            var resultXml;
            LookupFieldObject = Xrm.Page.data.entity.attributes.get('regardingobjectid');
            if (LookupFieldObject.getValue() != null) {
                EntityId = LookupFieldObject.getValue()[0].id;
                EntityName = LookupFieldObject.getValue()[0].entityType;
                resultXml = RetrieveEntityById(EntityName, EntityId, 'customerid');
                if (resultXml != null && resultXml.selectSingleNode('//q1:customerid') != null) {
                    var lookupValue = new Array();
                    lookupValue[0] = new Object();                  
                    lookupValue[0].id = resultXml.selectSingleNode('//q1:customerid').nodeTypedValue;
                    lookupValue[0].name = resultXml.selectSingleNode('//q1:customerid').getAttribute("name");
                    lookupValue[0].entityType = 'account';

                    Xrm.Page.data.entity.attributes.get('targetfieldname').setValue(lookupValue);
                }
            }
        }
    }
//Do not make any changes
function RetrieveEntityById(prmEntityName, prmEntityId, prmEntityColumns) {
    var resultXml, errorCount, msg, xmlHttpRequest, arrayEntityColumns, xmlEntityColumns;
    arrayEntityColumns = prmEntityColumns.split(",");
    for (var i = 0; i < arrayEntityColumns.length; i++) {
        xmlEntityColumns += "<q1:Attribute>" + arrayEntityColumns[i] + "</q1:Attribute>";
    }
    var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();
    //Prepare the SOAP message.
    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'>" +
    authenticationHeader +
    "<soap:Body>" +
    "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entityName>" + prmEntityName + "</entityName>" +
    "<id>" + prmEntityId + "</id>" +
    "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
    "<q1:Attributes>" +
    xmlEntityColumns +
   "</q1:Attributes>" +
    "</columnSet>" +
    "</Retrieve></soap:Body></soap:Envelope>";
    //call function to create Soap Request to ms crm webservice
    xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    resultXml = xmlHttpRequest.responseXML;
    var errorCount = resultXml.selectNodes('//error').length;
    if (errorCount != 0) {
        var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
        alert("Error Message : " + msg);
    }
    else {
        return resultXml;
    }
}

After adding the javascript to webresources you need to call setLookupfield() function on page on-load event on the target entity.