Monday, October 1, 2012

CRM 2011- Set ribbon button visiblity using javascript by Custom Rule



1. Create a web resource (jscript) with the following code.

function GetRelatedRecords() {
    var baseEntityGUID = Xrm.Page.data.entity.getId();
    var query = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"
        + " <entity name='jmh_guncurrentlocation'>"
  + "  <attribute name='jmh_locationdetail' />"
  + "    <attribute name='createdon' />"
   + " <attribute name='jmh_locationrfd' />"
   + " <attribute name='jmh_locationcustomer' />"
   + " <attribute name='jmh_gun' />"
    + " <attribute name='jmh_store' />"
   + " <attribute name='jmh_guncurrentlocationid' />"
   + " <order attribute='jmh_locationdetail' descending='false' />"
   + "<filter type='and'>"
    + "  <condition attribute='statecode' operator='eq' value='0' />"
     + " <condition attribute='jmh_gun' operator='eq' uiname='45' uitype='jmh_gun' value='" + baseEntityGUID + "' />"
    + "</filter></entity></fetch>";
    var retrievedRecords = XrmServiceToolkit.Soap.Fetch(query);
    //alert(retrievedRecords.length);
    if (retrievedRecords.length != 0) {

        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;
        for (var index = 0; index < retrievedRecords.length; index++) {

            var storeid = retrievedRecords[index].attributes['jmh_store'].id;

//            alert(buid);
//            alert(storeid);
            if (buid.toString() == storeid.toString()) {
                return true;
            }
        }
        return false;

    }
    else {
        return false;
    }
}

2.Create a button using visual ribbon editor and specify the created javascript method in cutom rule
 
Note : the above javascript to retrive related entities using Fetch in xrmservicetoolkit

No comments:

Post a Comment