Creating Connection using WebAPI- {Sample Code}

If you are looking for sample code to create connection record using WebAPI for Dynamics 365 CE, this post will help you. I am creating connection record for opportunity, you can change lookups entity based on your requirement.

function CreateConnection() {
    //get opportunity id
    var opportunityid = Xrm.Page.data.entity.getId().substring(1, 37); //remove {}

    //get owner of opportunity
    var ownerid = Xrm.Page.getAttribute("ownerid").getValue()[0].id;
    ownerid = ownerid.substring(1, 37); //remove {}

    //get server url
    var serverURL = Xrm.Page.context.getClientUrl();

    //prepare entity object
    var connection = {};
    //set record1id lookup with opportunity
    connection["record1id_opportunity@odata.bind"] = "/opportunities(" + opportunityid+ ")";

    //set record2id lookup with opportunity owner
    connection["record2id_systemuser@odata.bind"] = "/systemusers(" + ownerid + ")";
    //setup connection role
    connection["record2roleid@odata.bind"] = "/connectionroles(EA5B38CE-A5EE-4CA0-A339-3A51B7DA87FE)"; //connection role

    connection.effectiveend = new Date();

    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/connections", true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 204) {
                Xrm.Utility.alertDialog('Connection Created...');
            } else {
                Xrm.Utility.alertDialog("Error while creating Connection"+this.statusText);
            }
        }
    };
    req.send(JSON.stringify(connection));
}

Hope it will help someone !!

Leave a Reply

Your email address will not be published. Required fields are marked *