Search code examples
javascriptdynamics-crmxrmdynamics-365

How to add in the subject tree a new item with Xrm (Dynamics 365)


I need help to add a new item in the subject tree of dynamics 365, with Xrm and javascript.


Solution

  • Subject is like any other entity, you can use web api to create it.

    function createSubject() {
    
        var serverURL = Xrm.Page.context.getClientUrl();
        var subject = {};
        subject["title"] = "test subject"; 
        subject["featuremask"] = 1;
    
        //subject["[email protected]"]="/subjects(<GUID without Quotes>)";  //setting existing lookup
    
        subject["parentsubject"] = {
            "title": "test parent subject",
            "description": "deep insert to add parent before child",
            "featuremask": 1  
        };
    
        var req = new XMLHttpRequest();
        req.open("POST", serverURL + "/api/data/v8.2/subjects", 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 /* complete */ ) {
                req.onreadystatechange = null;
                if (this.status == 204) {
                    var subjectUri = this.getResponseHeader("OData-EntityId");
                } else {
                    var error = JSON.parse(this.response).error;
                    alert(error.message);
                }
            }
        };
        req.send(JSON.stringify(subject));
    }