Microsoft Dynamics CRM 2011

Microsoft Dynamics CRM 2011
Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Wednesday, December 30, 2020

How to find and debug your custom Javascript files in Dynamics CRM / 365

In this article we describe Step by step How to find and debug your custom Javascript files in Dynamics CRM / 365 in 5 minutes.
After you have coded you javascript files, you want to find them for debugging purposes. It could be a not easy task to find them between the hundreds of source files that Dynamics 365 will load to the browser:




How to find and debug your custom Javascript files in Dynamics CRM / 365

To debug quickly your javascript files, just follow this steps:

1) Open the FORM of the Entity your are working on, and go to the Properties of the Form. Open the Web Resources and find the JAVASCRIPT LIBRARY that you want to debug. Double-click it to open the editor:



2) Once opened the Editor, type into your  javascript file , the "debugger; " command:



3) Save it, save the Form, Publish it and open the Developer's Tools of the browser:


4) Then , just perform the Click or anything else that would trigger your javascript code: from here, you can add breakpoints to stop the script execution.
That's all...
In this article we've seen Step by step How to find and debug your custom Javascript files in Dynamics CRM / 365 in 5 minutes.
Enjoy Microsoft Dynamics 365 CRM!

by Carmel Schvartzman

כתב: כרמל שוורצמן










    Tuesday, April 16, 2019

    Dynamics 365 - How to Update Entity attributes using Web API and Javascript in 5 minutes

    In this article we describe Step by step How to Update Entity attributes using Web API and Javascript in 5 minutes.
    In this example, we send an HTTP PATCH request to the Dynamics 365 Web Api, in order to update several attributes, and also a MANY-TO-ONE relationship reference between Phonecall and Contact.
    We use the HTTP PATCH verb since we are updating more than ONE attribute. Elsewhere, we should use the HTTP PUT OData REST method.


    How to Update Entity attributes using Web API and Javascript in 5 minutes  



    The following code sends an HTTP PATCH request to the Dynamics 365 Web Api, in order to update several attributes, and also a MANY-TO-ONE relationship reference between Phonecall and Contact:



     var fnPATCHEntity = (newEntityId) => {
                //debugger;
                var entity = {};
                entity.phonenumber = document.getElementById("Phone").value;            
                entity.description = document.getElementById("Description").value;
                entity["regardingobjectid_contact@odata.bind"] = "/contacts(" + newEntityId + ")";
                let id = parent.Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');


                $.ajax({
                    type: "PATCH",
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    url: Xrm.Page.context.getClientUrl() + "/api/data/v8.2/phonecalls(" + id + ")",
                    data: JSON.stringify(entity),
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
                        XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
                        XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    },
                    async: true,
                    success: function (data, textStatus, xhr) {
                        Xrm.Utility.alertDialog('Phonecall Updated with MANY-TO-ONE relationship!!');
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
                    }
                });

            }




    That's all...
    In this article we've seen Step by step How to Update Entity attributes using Web API and Javascript in 5 minutes.
    Enjoy Microsoft Dynamics 365 CRM!

    by Carmel Schvartzman

    כתב: כרמל שוורצמן

    Dynamics 365 - How to Create a new Entity record using Web API and Javascript in 5 minutes

    In this article we describe Step by step  How to Create a new Entity record  using Web API and Javascript in 5 minutes. We'll use the JQuery already loaded by Dynamics 365 on the form.

    For this example, we'll create a Contact record, when clicking a button, using a Web Resource locally inside the Form.


    How to Create a new Entity record  using Web API and Javascript in 5 minutes



    This is the function to Create a Record , using an HTTP POST request: 


    var entity = {};
    entity.address1_telephone1 = "";
    entity.emailaddress1 = "";
    entity.lastname = "";

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contacts",
        data: JSON.stringify(entity),
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
            XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        async: true,
        success: function(data, textStatus, xhr) {
            var uri = xhr.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];
        },
        error: function(xhr, textStatus, errorThrown) {
            Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
        }
    });



    And this is the Web Resource EMBEDDED in the Form (that's why we wrote "parent" before calls to JQuery ) :
    1) Open the Form
    2) Add > Section > Web Resource
    3) Paste inside it the following HTML - JS code:



    <html><head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script>

    var fnCreateContact = () => {
    var entity = {};
    entity.address1_telephone1 = "123123123";
    entity.emailaddress1 = "www.bender.com";
    entity.lastname = "Contact Name";

    parent.$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: parent.Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contacts",
        data: JSON.stringify(entity),
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
            XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        async: true,
        success: function(data, textStatus, xhr) {
            var uri = xhr.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];

    document.getElementById('btnCreateContact').classList.add('disabled');
        },
        error: function(xhr, textStatus, errorThrown) {
            parent.Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
        }
    });
    }
    </script>
    <meta></head><body style="direction: rtl; overflow-wrap: break-word;">

    <div class="container">
      <div class="jumbotron">
        <h3>Create Contact</h3>   
        <p>This function creates a new Contact</p>
         <button id="btnCreateContact" onclick="fnCreateContact()" type="button" class="btn btn-primary">Create Contact</button>
      </div>
    </div>

    </body></html>






    That's all...
    In this article we've seen Step by step  How to Create a new Entity record  using Web API and Javascript in 5 minutes.
    Enjoy Microsoft Dynamics 365 CRM!

    by Carmel Schvartzman

    כתב: כרמל שוורצמן

    Step by step How to Install the CRM REST Builder in your Dynamics CRM 365 in 5 minutes

    In this article we describe Step by step How to Install the CRM REST Builder in your Dynamics CRM 365 in 5 minutes.
    The CRM REST Builder is an open source creation by  Jason Lattimer. It will give you the chance of getting the REST OData code that you need, both using JQuery or XMLHttpRequest, automatically and avoiding to fall on errors. The Builder enables you to perform WEB API OData REST request to create One to Many , Many to One and Many to Many relationships, asynchronously:



    How to Install the CRM REST Builder in your Dynamics CRM 365 in 5 minutes

    1) Download the REST BUILDER:
    Browse to the Jason Lattimer's Github , and download the Builder , according to your Dynamics CRM version: https://github.com/jlattimer/CRMRESTBuilder/releases



    2) Import the Managed Solution to your Dynamics 365:
    Open your solutions screen, and import the REST Builder solution:



    3) Open the REST BUILDER:
    After refreshing the Solutions form, you will see a button on the top of the form. Open it to see the Builder:





    4) Create your REST request:

    Create your request, and copy it to the web resource that will be called from your entity form:








    That's all...
    In this article we've seen Step by step How to Install the CRM REST Builder in your Dynamics CRM 365 in 5 minutes.
    Enjoy Microsoft Dynamics 365 CRM!

    by Carmel Schvartzman

    כתב: כרמל שוורצמן










      Sunday, July 5, 2015

      How to Add a custom Button to a CRM 2013 Web Form

      In this article we see Step by step How to Add a custom Button to a CRM 2013 Web Form .
      We'll review here in only 5 minutes how to create an HTML5 Button at the client side Front End , using only javascript, HTML and CSS3:




      The steps are as following:
      1) create a CRM field to be the container of the button(set its text as ".")
      2) create a web resource containing the following javascript
      3) call the web resource from your CRM form, sending as argument the name of your container field.


      1) Step #1: create a CRM field to be the container of the button:


      The button will be located at the CRM field (called "sFieldName" in the following code).
      Try to create a new CRM field to parent the button, and set "." as its text. This way the button will fill the field, and you can locate it wherever you want inside the CRM form.

      2) Step #2: create a web resource containing the following javascript:

      This is the code that creates the Button:
      It just retrieves the HTML5 element wrapping the CRM field where you want the button appended to, and creates an element with a custom button:





      Create a Web Resource with the following javascript code (note: this code does not depend on jQuery or any other framework: you can copy-paste it as it is):

      function fnXRMClientButton(sFieldName)
      {   // sFieldName : "new_somefield"
          
          if (document.getElementById(sFieldName) != null) {
               sFieldName = "field" + sFieldName;
               if (document.getElementById(sFieldName) == null)
               {
                  var oParentElement = document.getElementById(sFieldName + "_d");
                  oContainerElement = document.createElement("oContainerElement");
                  oParentElement.appendChild(oContainerElement, oParentElement);
                  
                  var btn = document.createElement("button");
                  var txt = document.createElement("span");
                  txt.innerText = "BUTTON TEXT";            
                  btn.id = "btnCallAction";
                  btn.appendChild(txt);
                  btn.style.margin = "10px";
                  btn.style.padding = "5px";
                  btn.style.width = "300px";
                  btn.style.height = "50px";
                  btn.style.textAlign = "center";
                  btn.style.borderRadius = "5px";
                  btn.style.textShadow = "1px 1px 2px #FFF";
                  btn.style.color = "#000";
                  btn.style.boxShadow = "#a8a3a3 5px 5px 1px";           
                  btn.style.border = "1px double #dcdcdc";           
                  btn.style.background = "#f5f5f5";
                  btn.style.font = "600 14px Tahoma";
                  oContainerElement.appendChild(btn);


                  document.getElementById(sFieldName).style.width = "0%";
                  btn.onclick = function () {
                      OnClickActionFunction(oContainerElement);

                  };

              }
          }
      }


      3) Step #3: call the web resource from your CRM form, sending as argument the name of your container field:


      fnXRMClientButton("new_somefield")


      That's all.  

      Happy programming.....

            by Carmel Schvartzman


      כתב: כרמל שוורצמן



      Monday, October 28, 2013

      Step-By-Step How to create a Ribbon Button in CRM 2011

      by Carmel Schvartzman
      1. In this walkthrough we will learn how to create a Ribbon Button in CRM 2011. We'll be adding a custom button called "Custom action" to the "Collaborate" group of the Case ribbon. By pressing that button, an action coded in javascript will fire. The javascript code will reside in a Web Resource. A Web Resource is a virtual html, jscript, css, picture or Silverligth file stored in the CRM database, and identified by a unique URL. After its creation, a Web Resource can be used in several CRM Forms, enhancing its functionality and/or appeareance. The custom ribbon button will appear as follows:


      How to create a Ribbon Button in CRM 2011

      1. We'll add a button to the ribbon by modifying the XML that defines its structure. In order to do that, we need to get that XML, exporting a solution wich contains the entity form we want to customize. Let's create that solution: press "New" at Solutions:
        How to create a Ribbon Button in CRM 2011
      2. Next, give it a relevant name, and fill the required fields:
      3. Then, Add to the solution the Case by clicking "Add Existing...Entity":
      4. Add to the Solution the Case entity:
      5. Publish the Solution and click on "Export Solution":
      6. Click "Next" and go to the next dialog:
      7. Select "Unmanaged" because we don't want to distribute this solution to other people, and Export it:
      8. Save the ZIP file to some address in your machine:
      9. Find the ZIP file and open it:
      10. From the unzipped folder, we only need to modify the "customizations.xml" file, so make a backup of it, and open the xml in any text editor you like, like Notepad++:
      11. Make a search on it to find the "RibbonDiffXml" element:
      12. Take a close look to it: this element is just a skeleton to create a custom button:
      13. Now let's take a look to the DYNAMICS CRM documentation at MSDN:

      14. In the XML we define the display rules that will guide the action performed by the custom ribbon button we are designing. There is a sample that sets a "DISPLAY RULE" only in case of an entity "Create" action:  ( the "display" rules documentation is here )

      15. There are several rules for the entity state. We need to select the "Existing" option, because we want to apply this button to existing entities:
      16. Find the "RULE DEFINITIONS" element: we'll modify it: ( the "enable" rules documentation is here ))
      17. Therefore, modify the "RULE DEFINITIONS" element as follows:


        This is the code to type:

         <RuleDefinitions>
              <TabDisplayRules />
              <DisplayRules />
             <EnableRules>
              <EnableRule Id="new.EnableRule.NewAction">
                <FormStateRule State="Existing" />
              </EnableRule>
             </EnableRules>
          </RuleDefinitions>
      18. Now, we'll define the ACTION performed by the custom button, so find the "CUSTOM ACTIONS" section:
      19. Again at the CRM documentation, examine the Ribbon Commands elements: ( the "commands" documentation is here  )

      20. You'll find out that we can attach a javascript function to a custom ribbon button in CRM 2011:  ( the "actions" documentation is here ) :
      21. According to the documentation, modify the "CUSTOM ACTION" element as follows:

        <CustomAction Id="new.CustomAction.NewAction" Location="Mscrm.Form.incident.MainTab.Collaborate.Controls._children" Sequence="27">


        Be careful to change the entity logic name to the entity you are intending to customize. In this example, the entity is "Case" and its logical name is "incident". Change it to adapt to your needs. Also, change the "Collaborate" ribbon group to the one you want to add your button to. The "Sequence" is the place inside the ribbon group in wich your button will be displayed, so choose any number greater to the number of buttons in it.
      22. Type some relevant text for the button LABEL and for the TOOLTIP you want to be displayed:

          <CommandUIDefinition>
                  <Button Id="new.Button.NewAction"
                          Command="new.Command.NewAction"
                          LabelText="Custom Action"
                          ToolTipTitle="Execute Action"
                          ToolTipDescription="Press the Custom Button to display an JS message"
                          TemplateAlias="o1"
                          Image16by16="/_imgs/Ribbon/Entity16_4210.png"
                          Image32by32="/_imgs/Ribbon/Entity32_4210.png" />
                </CommandUIDefinition>


      23. Now, for the picture in the button, i'll be using a CRM picture, stored in the CRM 2011 site, in the "_imgs" folder:
      24. Add the selected pictures to both 16 pixels and 32 pixels fields:
      25. Now, for the linking between the button and the javascript function, we'll need to customize the "COMMAND DEFINITIONS" element, so find it:
      26. Type the following code , and take a look at the relation between the button and the command definition:

         <CommandDefinitions>
              <CommandDefinition Id="new.Command.NewAction">
                <EnableRules>
                  <EnableRule Id="new.EnableRule.NewAction" />
                </EnableRules>
                <DisplayRules>
                  <DisplayRule Id="Mscrm.CanWritePrimary"/>
                </DisplayRules>
                <Actions>
                  <JavaScriptFunction Library="$webresource:new_ribbonbuttonjs"                     FunctionName="DisplayMsg">
                  </JavaScriptFunction>
                </Actions>
              </CommandDefinition>
            </CommandDefinitions>



        As you can see, we'll be using a Web Resource called "new_ribbonbuttonjs", which includes a javascript function "DisplayMsg". We'll build such Web Resource later in this tutorial.
      27. Now let's import back our XML , with the modified ribbon. ZIP the 3 files and ...
      28. ... import them back to CRM 2011:
      29. First browse to the ZIP file folder:
      30. Ignore the warning you'll get :
      31. Import the XML ribbon customizations:
      32. And don't forget to publish the changes:
      33. If you get a FAIL message, check the details for the cause of them:

        For instance, in this case CRM didn't find the Web Resource required
      34. Therefore, let's create that Web Resource. Go to New Web Resource, and give it exactly the same name you set at the XML file:

        Our javascript function will just open an alert window to display a message. Type the function inside the Text Editor of the Web Resource.
      35. Publish the Web Resource:
      36. Finally, open some Case form entity. You'll be acknowledge with our brand new ribbon button:

        Also you'll see the tooltip of the custom control.
      37. And pressing our custom button fires the javascript code we just created:
      38. In this tutorial we saw How to create a Ribbon Button in CRM 2011. That's all...Enjoy Dynamics CRM  !!!


        כתב: כרמל שוורצמן