Translate

Sunday 22 December 2013

Add a button on CRM 2013 form

How to add a button in CRM 2013 form ?

Hello CRM Developers,
          This is my new post to add a new button in CRM 2013.

I can understand the CRM developers requirements, because after release of CRM roll up 12 and CRM 2013, we can access CRM on cross browsers also. when we did customization with java script functionality, It may vary browser to browser, so there may be need of yours to add a custom button in CRM 2013. So here is the simple java script code for CRM 2013 and it will work in CRM 2011(rollup 12) as well as in CRM 2013.

Step 1:- Add a attribute of type single line text on crm 2013 form. Or you may use existing one.

Step 2:- Add the fallowing code to your crm java script web resource. And call this function on page load.
     
function createButton() {
        var atrname = "YOUR ATTRIBUTE SCHEMA NAME";
        if (document.getElementById(atrname ) != null) {
        var fieldId = "field" + atrname ;
        if (document.getElementById(fieldId ) == null) {
            var elementId = document.getElementById(atrname + "_d");
            var div = document.createElement("div");
            div.style.width = "100px";
            div.style.textAlign = "right";
            div.style.display = "inline";


            childDiv = elementId.getElementsByTagName('div')[0]
            childDiv.style.display = "none";

            elementId .appendChild(div, elementId );
            div.innerHTML = '<button id="' + fieldId + '"  type="button" style="margin-left: 3px; width: 100%;" >CRM Form Button</button>';
            document.getElementById(atrname).style.width = "0%";
            document.getElementById(fieldId ).onclick = function () { YourOnClickFunction(); };
        }
    }
}

 

Sunday 1 December 2013

retrieve with java script in crm 2013

Replacement of SOAP in CRM for single record retrieve in java script.

Hello CRM Lovers,
    First of all thanks for reading my post. As we all know that after CRM Roll-Up 12, SOAP has stopped working for cross browser support in CRM, so we have to write some other code to solve this problem. I found a way to solve this problem so I am sharing it with the beautiful world.
 
    In this post I am going to describe how to retrieve single record with java script of another entity in CRM 2011, CRM 2013 with JSON and OData.It will work on Roll-Up 12, Roll-Up 13 for CRM 2011 and on CRM 2013, and also in cross browsers. It will really help you. For retrieving data please fallow these steps.

  Retrieve Single Record with Java Script in CRM 2013

  Retrieve Multiple Records with Java Script in CRM 2013

  Step 1:-  First of all you have to add this function in your web resource.

//***********************************************************************************************************************
 //*******Retrive Single recored on the basis of the criteria OData Rest //******************************************************************************************

function retrieveRecord(id, odataSetName, successCallback, errorCallback, _excontext) {
    var context = Xrm.Page.context;
    _executionObj = _excontext;
    var serverUrl = context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

    //id is required 
    if (!id) {
        alert("record id is required.");
        return;
    }     //odataSetName is required, i.e. "AccountSet"
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }
    //Asynchronous AJAX function to Retrieve a CRM record using OData
    $.ajax({
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.      
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (successCallback) {
                successCallback(data.d, textStatus, XmlHttpRequest);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}

function errorHandler(xmlHttpRequest, textStatus, errorThrow) {
    alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
}


Step 2 :-  Now add the fallowing functions with your custom code. Suppose you want to retrieve a record of a entity then write your function in this format.

//**********************************************************************************//*****************Your custom function for retrieving data********************
//**********************************************************************************
    function FunctionName() {
        var recordId= "guid of the record";
       if (_condition!= null) {
             retrieveRecord(recordId, "EntitySet", getRecord, null, null);
        }
    }

//****************************************************************//****************************************************************

    function getRecord(data, textStatus, XmlHttpRequest) {
        //debugger;      
      if (data != null) {
            
                var attribute1 = data.attribute1 schema name;
                var attribute2 = data.attribute2 schema name;
          
        }
    }

Here  "data" is object of  retrieved records you can find  your required attribute accordingly.

For more info you can visit.

http://msdn.microsoft.com/en-us/library/gg309461.aspx

http://msdn.microsoft.com/en-us/library/hh169248%28v=nav.71%29.aspx

Or you can download odata query designer from this link from here you will get a managed solution import it in your organization and design your odata query according to your requirement. 

http://crm2011odatatool.codeplex.com/


So by fallowing all upper steps you can retrieve records . It will work in cross browser and in all new Roll-Up 12,Roll-Up 13 . 

Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 
Thanks.

Saturday 16 November 2013

Detect browser in crm 2013

How to detect browser in CRM ?

Hello CRM Lovers,
          Here is my findings, In this post i will share with you how to detect browser in CRM. It is not a big task, easy one.

I can understand the CRM developers requirements, because after release of CRM roll up 12 and CRM 2013, we can access CRM on cross browsers also. when we did customization with java script functionality, It may vary browser to browser, so there may be need of browser detection in CRM 2011 and in CRM 2013. So here is the simple java script code for CRM and it will work in CRM 2011(rollup 12) as well as in CRM 2013.

Add the fallowing code to your crm java script web resource.



         Mscrm.Utilities.isIE = function() {
             return Sys.Browser.agent === Sys.Browser.InternetExplorer
         };

         function detectBrowser() {
            if (Mscrm.Utilities.isIE()) {
               alert("You are using IE");
            }
             if (Mscrm.Utilities.isFirefox()) {
               alert("You are using Firefox");
           }
            if (Mscrm.Utilities.isChrome()) {
               alert("You are using Chrome");
           }
      }


Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 

Tuesday 5 November 2013

Retrieve data in crm 2013

Replacement of SOAP in CRM for retrieve data with java script.

Hello CRM Lovers,
    First of all thanks for reading my post. As we all know that after CRM Roll-Up 12, SOAP has stopped working for cross browser support in CRM, so we have to write some other code to solve this problem. I found a way to solve this problem so I am sharing it with the beautiful world.
 
    In this post I am going to describe how to retrieve data with java script of another entity in CRM 2011, CRM 2013 with JSON and OData.It will work on Roll-Up 12, Roll-Up 13 for CRM 2011 and on CRM 2013, and also in cross browsers. It will really help you. For retrieving data please fallow these steps.

  Retrieving Multiple Records with ODATA in CRM with Java Script

  Java script for retrieving data in cross browser

Step 1:-  First of all you have to add this function in your web resource.

//***********************************************************************************************************************
 //*******Retrive Multiple recored on the basis of the criteria OData Rest //******************************************************************************************

function retrieveMultiple(odataSetName, filter, successCallback, errorCallback, _executionObj) {
    _executionObjMultiretrive = _executionObj;
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    //odataSetName is required, i.e. "AccountSet"  
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }
    //Build the URI 
    var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName;
    //If a filter is supplied, append it to the OData URI
    if (filter) {
        odataUri += filter;
    }
    //Asynchronous AJAX function to Retrieve CRM records using OData
    $.ajax({
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        datatype: "json", url: odataUri,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (successCallback) {
                if (data && data.d && data.d.results) {
                    successCallback(data.d.results, textStatus, XmlHttpRequest);
                }
                else if (data && data.d) {
                    successCallback(data.d, textStatus, XmlHttpRequest);
                }
                else {
                    successCallback(data, textStatus, XmlHttpRequest);
                }
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}
function errorHandler(xmlHttpRequest, textStatus, errorThrow) {
    alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
}


Step 2 :-  Now add the fallowing functions with your custom code. Suppose you want to retrieve all the records from a entity which has single line text attribute and its value = "multiple retrieve with odata". for this condition you can use this code.

//**********************************************************************************//*****************Your custom function for retrieving data********************
//**********************************************************************************
    function YourFunction() {
        var _condition= "multiple retrieve with odata";
       if (_condition!= null) {
             retrieveMultiple("Entity NameSet", "?$filter=Attribute Schema Name eq '"+_condition+"' ", RetrieveEntityRecords, null, null);
        }
    }

//****************************************************************//****************************************************************

    function RetrieveEntityRecords(data, textStatus, XmlHttpRequest) {
        //debugger;      
      if (data.length > 0) {
             for (i = 0; i < data.length; i++) {
                var attribute1 = data[i].attribute1 schema name;
                var attribute2 = data[i].attribute2 schema name;
           }
        }
    }

Here  "data" is object of all retrieved records, you can find  your required attribute accordingly.


I know your condition may be differ.

The filter condition differs on the basis of attribute type so you can visit this link for more conditions...

http://msdn.microsoft.com/en-us/library/gg309461.aspx

http://msdn.microsoft.com/en-us/library/hh169248%28v=nav.71%29.aspx

Or you can download odata query designer from this link from here you will get a managed solution import it in your organization and design your odata query according to your requirement. 

http://crm2011odatatool.codeplex.com/


So by fallowing all upper steps you can retrieve records . It will work in cross browser and in all new Roll-Up 12,Roll-Up 13 . 

Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 
Thanks.

Friday 9 August 2013

Get current user role and name in rollup 14

  How to get "Current User Role and Role Name" in CRM for roll-up 14. 

     Hello CRM lovers, Here is my blog for  getting logged user Role and Role name for Roll-Up 12, Roll-Up 13, Roll-Up 14 and also in cross browser support. I will really help you. For achieving this you have to fallow these steps.

 

Step 1:-  First of all you have to add reference of J Query main file minimum version jquery1.4.1.min or higher version. you can download it from http://jquery.com/.

Step 2:-  Now you have to add reference of "json2" on your crm entity form, You can get it from sdk, you will find it in your sdk folder.

Step 3:-  Now add the fallowing code in your web resource. 



//******************************************************************************************
//*******Retrive Multiple recored on the basis of the criteria OData Rest Method************
//******************************************************************************************
function retrieveMultiple(odataSetName, filter, successCallback, errorCallback, _executionObj) {
    _executionObjMultiretrive = _executionObj;
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    //odataSetName is required, i.e. "AccountSet"  
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }
    //Build the URI 
    var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName;
    //If a filter is supplied, append it to the OData URI
    if (filter) {
        odataUri += filter;
    }
    //Asynchronous AJAX function to Retrieve CRM records using OData
    $.ajax({
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        datatype: "json", url: odataUri,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (successCallback) {
                if (data && data.d && data.d.results) {
                    successCallback(data.d.results, textStatus, XmlHttpRequest);
                }
                else if (data && data.d) {
                    successCallback(data.d, textStatus, XmlHttpRequest);
                }
                else {
                    successCallback(data, textStatus, XmlHttpRequest);
                }
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}
function errorHandler(xmlHttpRequest, textStatus, errorThrow) {
    alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
}


Step 4 :-  Now add the fallowing three functions in your web resource, In third function you will get current logged user role name.

//**********************************************************************************
//***************** Function For getting the Current User Role********************
//**********************************************************************************
    function getOwnerRole(UserID) {
        var _Userid = UserID;
        if (_Userid != null) {
            var istrue = retrieveMultiple("SystemUserRolesSet", "?$filter=SystemUserId eq (guid'" + _Userid + "')", RetrieveDataFromSystemUser, null, null);
        }
    }

    function RetrieveDataFromSystemUser(data, textStatus, XmlHttpRequest) {
        //debugger;
        var executioncontext = _executionObjMultiretrive;
        var len = data.length;
        if (len > 0) {
            for (i = 0; i < len; i++) {
                if (data[i].RoleId != null) {

 //****************************************************************
//*** This is the first role user have
//*** User may have many roles so you can get all here during loop                    //******************************************************************************
      var userRoleId=data[0].RoleId;

      retrieveMultiple("RoleSet", "?$filter=RoleId eq (guid'" + data[i].RoleId + "')",         RetrieveRoleName, null, null);
                }
            }
        }
    }

    function RetrieveRoleName(data, textStatus, XmlHttpRequest) {
        //debugger;
        var executioncontext = _executionObjMultiretrive;
        var len = data.length;

        if (data[0].Name != null) {

              var userRoleName=data[0].Name;          
        }
    }           



So by fallowing all upper steps you can get current logged user Role Id and Role Name. It will work in cross browser and in all new Roll-Up 12,Roll-Up 13 and Roll-Up 14. 

Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 
Thanks.

Tuesday 23 July 2013

How to get CRM entity attribute value in HTML web resource

  Today i got the requirement of getting CRM entity attribute value in the html web resource which was attached with the crm entity or called on clicking on a navigation link or from a ribbon button.

    You can get parent window object and then you can get object of crmForm then you will get all attribute of entity as well as their values.

For CRM 2011 

var attrVal = window.parent.document.crmForm.<Attribute Name>.value;


For CRM 2013

var attrVal = window.parent.document.Xrm.Page.getAttribute("<Attribute Name>").getValue();


Step 1:- Add a HTML web resource which you want to use.

Step 2:- Add a java script function with the fallowing code in the head section of the HTML web resource.

 <script type="text/javascript" src="ClientGlobalContext.js.aspx"></script>
               <script type="text/javascript">
                   function ABC() {
                       debugger;
                       var form = document.forms[0];
                       var context = GetGlobalContext();
                       var attrVal = window.parent.document.crmForm.<Attribute Name>.value;   
                       // Your code for your functionality                                                                                            }
 </script>
<meta charset="utf-8">
Step 3:- Call java script function on body on load.

<body onload="ABC()">
  
   <form method="post" action="">
    //******************************************
    //********* your HTML **********************
    //******************************************
   </form>

</body>
Your final HTML web resource will look like.
 
<html>
     <head>
          <title> </title>
               <script type="text/javascript" src="ClientGlobalContext.js.aspx"></script>
               <script type="text/javascript">
                   function ABC() {
                       debugger;
                       var form = document.forms[0];
                       var context = GetGlobalContext();
                       var attrVal = window.parent.document.crmForm.<Attribute Name>.value;
                          //******************************************                                  //********* your Custom Code **********************
              //******************************************
                           }
       </script>
<meta charset="utf-8"> 
  <body onload="ABC()">  
   <form method="post" action="">
    //******************************************
    //********* your HTML **********************
    //******************************************
    </form>
  </body>   
</html>

Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 

Thursday 13 June 2013

Current fiscal year in crm 2011

How to get current fiscal year in CRM 2011.  


   Here is my new update. In this update of mine you can know how to get current fiscal year in CRM on the basis of CRM fiscal year settings.

   Normally fiscal year starts on 1 April to 31 March, but CRM 2011 provides the feature to set our custom fiscal period because fiscal period may differ organization to organization, so there may be need of custom fiscal period, and if custom fiscal period exist then i am sure there will need of current fiscal year. Unfortunately CRM does not stores current fiscal year, so you have to calculate current fiscal year.So in this blog you can get current fiscal year.

Fallow these steps.

Step 1:-  Click on Settings tab.





Step 2:-  Open fiscal year year setting.


Step 3:-  Set the start date and other setting regarding fiscal year.


Step 4:-  Now write this java script code to get current fiscal year in any  variable, you can write this where you want to use current fiscal year.

function getCurrentFiscalYear() {

    //Get Current Date
    var today = new Date();
    var todayDate = today.getMonth() + 1 + "/" + today.getDate() + "/" + today.getFullYear();

    //For rollup 11
    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\">" +
        GenerateAuthenticationHeader() +
        "<soap:Body>" +
        "<RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
        "<query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
        "<q1:EntityName>organization</q1:EntityName>" +
            "<q1:ColumnSet xsi:type='q1:ColumnSet'>" +
                "<q1:Attributes>" +
                    "<q1:Attribute>fiscalcalendarstart</q1:Attribute>" +

                "</q1:Attributes>" +
            "</q1:ColumnSet>" +
        "<q1:Distinct>false</q1:Distinct>" +

        "</query></RetrieveMultiple>" +
        "</soap:Body></soap:Envelope>";

    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);

    var result = xmlHttpRequest.responseXML.xml;

    var doc = new ActiveXObject("MSXML2.DOMDocument");
    doc.async = false;
    doc.loadXML(result);

    if (doc.selectSingleNode("//q1:fiscalcalendarstart") != null) {

        var startDate = doc.selectSingleNode("//q1:fiscalcalendarstart").attributes[0].nodeTypedValue

        //Organisation Fiscal start date
        var sDate = new Date(startDate);

        var currentDate = new Date(todayDate);

        if (startDate <= todayDate) {

            var diff = currentDate.getFullYear() - sDate.getFullYear();

            var CurrentFiscalYear = (parseInt(sDate.getFullYear()) + parseInt(diff));

            // alert(CurrentFiscalYear);


        }
        else {

            var diff = sDate.getFullYear() - currentDate.getFullYear();

            if (parseInt(diff) == 0) {

                var CurrentFiscalYear = (parseInt(sDate.getFullYear()) - parseInt(1));
                //alert(CurrentFiscalYear);

            }
            else {
                var CurrentFiscalYear = (parseInt(sDate.getFullYear()) - parseInt(diff));
                //alert(CurrentFiscalYear);
            }
        }
    }
}


Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 

Monday 10 June 2013

How to Convert Option Set in to a Check Box list ?

How to Convert Option Set in to a Check Box list with java script.

Here is my new update, in this blog you can find the process and code to convert option set into a check box list. And one important thing is that it will work on CRM roll-up 11, CRM roll-up 12 and CRM roll-up 13. So just enjoy the great technology like CRM.

Step 1:- First Create option set which you want to convert into Checkbox list.
Step 2:- Create another attribute to store value of option set.
Step 3:- Add both the fields on the entity form.
Step 4:- Create new web resource or update existing web resource with the fallowing code.  

    function Form_onload() {

    var _crtlSociaklNW = document.getElementById("new_socialnetwork");
    var _crtlTextSocial = document.getElementById("new_textsocial");

    if (_crtlSociaklNW != null && _crtlTextSocial != null) {

        _crtlSociaklNW.style.display = "none";
        var pdiv = document.createElement('div');
        pdiv.style = 'overflow-y:auto; height:100px; border:1px #6699cc solid;          background-color:#ffffff;';
        _crtlSociaklNW.parentNode.appendChild(pdiv);
        ///////////////////////////////////////////////////////////////////////////
///////////////////// Convert option set to check box//////////////////////
///////////////////////////////////////////////////////////////////////////
        for (var i = 1; i < _crtlSociaklNW.options.length; i++) {
            var OptionSetItems = _crtlSociaklNW.options[i];
            if (!IsChecked(OptionSetItems.text, _crtlTextSocial)) {
                var addInput = document.createElement('input');
                addInput.type = 'checkbox';
                addInput.style.pixelWidth = 30;
            }
            else {
                var addInput = document.createElement('input');
                addInput.type = 'checkbox';
                addInput.checked = true;
                addInput.style.pixelWidth = 30;
            }

            var addLabel = document.createElement('label');
            addLabel.innerText = OptionSetItems.text;
            var addBr = document.createElement('br');
            var formname = Xrm.Page.getAttribute("new_name").getValue();

            _crtlSociaklNW.nextSibling.appendChild(addInput);
            _crtlSociaklNW.nextSibling.appendChild(addLabel);
            _crtlSociaklNW.nextSibling.appendChild(addBr);

        }
    }
}
///////////////////////////////////////////////////////////////////////////
///////////////// To check if which check box is selected//////////////////
///////////////////////////////////////////////////////////////////////////
function IsChecked(pText, _crtlTextSocial) {
    if (_crtlTextSocial.value != "") {
        var _crtlTextSocial = _crtlTextSocial.value.split(",");
        for (var i = 0; i < _crtlTextSocial.length; i++) {
            if (_crtlTextSocial[i] == pText)
                return true;
        }
    }
    return false;
}
///////////////////////////////////////////////////////////////////////////
///function to save the selected Items from check box list to TextSocial///
///////////////////////////////////////////////////////////////////////////
function Form_onSave() {
  
    var _crtlSociaklNW = document.getElementById("new_socialnetwork");
  
    var txtSocialValue = "";
    var getInput = _crtlSociaklNW.nextSibling.getElementsByTagName("input");

    for (var i = 0; i < getInput.length; i++) {
        if (getInput[i].checked) {
            txtSocialValue += getInput[i].nextSibling.innerText + ",";
        }
    }
    Xrm.Page.getAttribute("new_textsocial").setValue(txtSocialValue);

}

Step 5:- Now call Form_onload() function on Form OnLoad event and Form_onSave() function on             form OnSave event. And then save and publish form.
            Now your form will look like this.
Step 6:- Select check boxes and then save then it will look like this.
Step 7:- Now Hide TextSocial on the entity form.
Step 8:- Now it will look like.
 Soon i will write my new post "How to hide these check boxes on the basis of condition"

Enjoy the great technology Dynamics CRM. Good luck.....!!!!!