Microsoft Dynamics CRM 2011

Microsoft Dynamics CRM 2011
Showing posts with label Client Side. Show all posts
Showing posts with label Client Side. Show all posts

Friday, December 20, 2019

Deep Insert Request for Account Entity using AJAX on Dynamics 365


The following request body posted to the Account entity set will create a total of four new entities in the context of creating an account.
· A contact is created because it is defined as an object property of the single-valued navigation property primarycontactid.
· An opportunity is created because it is defined as an object within an array that is set to the value of a collection-valued navigation property opportunity_customer_accounts.
· A task is created because it is defined an object within an array that is set to the value of a collection-valued navigation property Opportunity_Tasks.The following is the source I used for this:

https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/create-entity-web-api#bkmk_CreateRelated


var fnDeepInsert = () => {

    let entityName = "accounts";
    let clientURL = parent.Xrm.Page.context.getClientUrl();
    let req = new XMLHttpRequest();

    req.open("POST", encodeURI(clientURL + "/api/data/v9.1/" + entityName, true));
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");

    req.onreadystatechange = function () {
        if (this.readyState == 4  ) {
            req.onreadystatechange = null;
            if (this.status == 204) {
                alert("No Content = Four Entities created using DEEP INSERT");
            }
            else {
                let error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };

    req.send(JSON.stringify(
        {
            name: "Account",
            primarycontactid:
            {
                firstname: "Bender",
                lastname: "Rodriguez"
            },
            opportunity_customer_accounts:
            [
             {
                 name: "Opportunity for Bender",
                 Opportunity_Tasks:
                 [
                  { subject: "Task related to Bender" }
                 ]
             }
            ]
        }));
}






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

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

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  !!!


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

    Tuesday, October 15, 2013

    Step-By-Step How to open a Dialog from Client Side using Javascript

    by Carmel Schvartzman
    1. In this walkthrough we will learn how to open a Dialog automatically from Client Side, using Javascript and a Web Resource, in Dynamics CRM 2011. A Web Resource is just a virtual file containing html, jscript, css, a picture or Silverlight , 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 appeareance. In our example, we will use a javascript Web Resource to launch a Dialog when an  CRM Form opens:

    2. First, we'll need a javascript code inside a Web Resource. Open the Web Resources:
    3. ... and create a New Web Resource:
    4. Give it a Display Name with a "_" to make the Web Resource appear at the top of the Web Resources list, and set the Type to script:
    5. Open the Text Editor and type the javascript function that will open the Dialog:

      The first parameter represents the CRM context, and the second will be the ID of the CRM Dialog we want to launch from the form.

    6. Let's stop the creation of the Web Resource for now, and go to the form of the entity you want to open the dialog from:
    7. To relate our Web Resource to the form, open the Form Properties:
    8. Add the  Web Resource to the Form Libraries:

    9. Find and open the Web Resource we just created:
    10. Next, add it as the Event Handler script that will run on a "OnLoad" event:
    11. The next step is to set what will be the function that will be called. Be careful to type exactly the same name you saved when you created the Web Resource:

      Also, pass the execution context as the function's first parameter.
    12. Now we have a little problem: the second parameter must be the ID of the Dialog we want to open. Where we can obtain the GUID of the Dialog? Well, that's a bit tricky. Go to the Dialog you want to launch:
    13. Open it, and click "Copy a Link" from the Actions menu:

      That will copy to the clipboard a URL containing the GUID of the Dialog.
    14. Go back to the Event Handler , and paste it to the parameters text box:
    15. You can see a URL and an "ID" in it: this is the GUID of the Dialog:
    16. So erase everything else , and close the GUID with quotes:
    17. Save the form and Publish it. Now we have the parameters we need . Get back to the Web Resource, and type the following code to get the Organization's server URL:
    18. Next, we need to determine the Entity Name and the ID of the Record represented by the CRM Form, so type the following code:
    19. Now we build the URL of the window that will open the dialog. Start with the server:
    20. ...  and link the Entity Name and ID to the URL:
    21. Finally , type the javascript code that opens the window dialog:
    22. And we're done...  Let's see how it works: open some Contact:
    23. ...  And you'll see that the selected CRM 2011 Dialog launchs automatically when the Form opens:






      That's all...Enjoy Dynamics CRM!!!


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