Microsoft Dynamics CRM 2011

Microsoft Dynamics CRM 2011
Showing posts with label JQuery Building Blocks. Show all posts
Showing posts with label JQuery Building Blocks. 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

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

Dynamics 365 - How to Create a MANY-TO-ONE related Entity record using Web API and Javascript in 5 minutes

In this article we describe Step by step How to Create a MANY-TO-ONE related Entity record using Web API and Javascript in 5 minutes.
This Web Resource uses Bootstrap and JQuery , to issue HTTP POST and HTTP PATCH requests to a Dynamics 365 Organization, using the Web Api, in order to Create a new Contact record, related to a current Phonecall. 

The UI looks like this :










How to Create a MANY-TO-ONE related Entity record using Web API and Javascript in 5 minutes  



There will be 2 functions, one for creating a new Contact record with HTTP POST , like this :





And the second function, in order to UPDATE the current Phonecall record, setting its Contact reference regardingobjectid_contact to the guid of the newly created Contact :






The following is the whole Web Resource, to be copied as a building block to your Dynamics Organization :


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

        // Create a MANY-TO-ONE relationship :  Créer une relation plusieurs-à-un phonecalls-contact :
        var fnPATCHRelatedEntity = (newEntityId) => {
            //debugger;
            var entity = {};
            entity["regardingobjectid_contact@odata.bind"] = "/contacts(" + newEntityId + ")";
            let id = parent.Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
            // In case you want to modify another attribute :  Au cas ou tu veux modifier un autre attribut :
            // entity.phonenumber = "0546589251";

            parent.$.ajax({     //  We can use HTTP PUT whenever we need to modify only ONE attribute
                type: "PATCH",  //  on peut utiliser le verbe HTTP PUT , dans le cas de modification de 1 seul attribut
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: parent.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) {
                    parent.Xrm.Utility.alertDialog('Phonecall Updated with MANY-TO-ONE relationship!!');
                },
                error: function (xhr, textStatus, errorThrown) {
                    parent.Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
                }
            });

        }

        var fnCreateContact = () => {
            //debugger;
            var entity = {};
            entity.address1_telephone1 = document.getElementById("Phone").value;
            entity.emailaddress1 = document.getElementById("Email").value;
            entity.firstname = document.getElementById("FirstName").value;
            entity.lastname = document.getElementById("LastName").value;

            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) {
                    let uri = xhr.getResponseHeader("OData-EntityId");
                    let regExp = /\(([^)]+)\)/;
                    let matches = regExp.exec(uri);
                    let newEntityId = matches[1];
                    if (newEntityId != null) {
                        // Créer une relation plusieurs-à-un phonecalls-contact :
                        fnPATCHRelatedEntity(newEntityId);
                    }


                    document.getElementById('btnCreateContact').classList.add('disabled');
                },
                error: function (xhr, textStatus, errorThrown) {
                    parent.Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
                }
            });
        }


    </script>

</head>
<body style="direction: rtl; overflow-wrap: break-word;">

    <div class="container">
        <div class="jumbotron">
            <h3>Create Contact</h3>
            <p></p><h5>This function creates a new Contact related to the current Phonecall through a One-To-Many relationship</h5><p></p>
            <table style="font:12px;border-spacing:3px;margin:5px;">
                <tbody>
                    <tr>
                        <td>First Name: </td>
                        <td><input type="text" id="FirstName" value="Bender"></td>
                    </tr>
                    <tr>
                        <td>Last Name: </td>
                        <td><input type="text" id="LastName" name="LastName" value="Rodriguez"></td>
                    </tr>
                    <tr><td>Email: </td><td><input type="text" id="Email" value="www.bender.com"></td></tr>
                    <tr>
                        <td>Phone: </td>
                        <td><input type="text" id="Phone" name="Phone" value="123456789"></td>
                    </tr>
                </tbody>
            </table>

            <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 MANY-TO-ONE related Entity record 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

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

Wednesday, April 10, 2019

Dynamics 365 - How to Retrieve Many-To-One related Entity attributes using Web API and Javascript

In this article we describe Step by step  How to Retrieve Many-To-One related Entity attributes using Web API and Javascript in 5 minutes. We use the JQuery included in the Dynamics form.
This is our example :  we want to get attributes from a Contact related to a Phonecall :
This is a MANY-TO-ONE relationship, therefore :
Primary Entity = Contact
Related Entity = Phonecall
Link Entity = regardingobjectid_phonecall_contact 
 (this logical name can be inferred from the N:1 link as seen in the Customizations : see this snapshot : )





How to Retrieve Many-To-One related Entity attributes using Web API and Javascript 



This approach works by creating only one web resource embedded into the Form HTML page of the entity :
1) Open the Form - Add a new Region
2) Add a Web Resource to the Region
3) Click on Create New Web Resource 
4) Add the following Building Block code to the Web Resource :

This code:
- loads Bootstrap
- uses JQuery form the Parent Form
- Gets Attributes from both the current Entity (Phonecall) + the related MANY-TO-ONE Entity (Contact) :


<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> 
   
    function fnGetContactDetails() {

      debugger;
      let gPrimaryEntityId = parent.Xrm.Page.data.entity.getId();

      if (gPrimaryEntityId) {

        gPrimaryEntityId = gPrimaryEntityId.replace("{", "").replace("}", "");

        parent.$.ajax({
          type: "GET",
          contentType: "application/json; charset=utf-8",
          datatype: "json",
          url: encodeURI(parent.Xrm.Page.context.getClientUrl() + "/api/data/v8.2/phonecalls(" + gPrimaryEntityId + ")?$select=activityid,phonenumber&$expand=regardingobjectid_contact_phonecall($select=contactid,fullname,accountrolecode,emailaddress1,telephone1,mobilephone,company)"),
          beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
            XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
          },
          async: true,
          success: function (data, textStatus, xhr) {
            var result = data;
            var activityid = result["activityid"];
            var phonenumber = result["phonenumber"];
            if (result.hasOwnProperty("regardingobjectid_contact_phonecall")) {
              var contactid = result["regardingobjectid_contact_phonecall"]["contactid"];
              var fullname = result["regardingobjectid_contact_phonecall"]["fullname"];
              let accountrolecode = result["regardingobjectid_contact_phonecall"]["accountrolecode"];
              let emailaddress1 = result["regardingobjectid_contact_phonecall"]["emailaddress1"];
              let telephone1 = result["regardingobjectid_contact_phonecall"]["telephone1"];
              let company = result["regardingobjectid_contact_phonecall"]["company"];
              let mobilephone = result["regardingobjectid_contact_phonecall"]["mobilephone"];


              document.getElementById("msg").innerHTML = fullname + "<br>" + // accountrolecode + "<br>" + 
                         emailaddress1 + "<br>" + telephone1 + "<br>" + company + "<br>" + mobilephone;

            document.getElementById("btnGetContact").style.display = "none";
              // parent.Xrm.Utility.alertDialog(fullname);
            }
          },
          error: function (xhr, textStatus, errorThrown) {
            parent.Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
          }
        });
      }
      else {
        parent.Xrm.Page.ui.alert("No ID for Primary Entity");
      }
    }

</script>
<meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta></head><body style="direction: rtl; overflow-wrap: break-word;">


<div class="container">
  <div class="jumbotron">
    <h3>Contact Details</h3> 
    <button id="btnGetContact" class="btn btn-secondary" onclick="fnGetContactDetails()">Get Contact Details </button> 
    <b><div id="msg"></div></b> 
</div>

</div></body></html> 
    
}







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

by Carmel Schvartzman

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