Creating Task entity record through rest in MS CRM 2011

In my Adding Convert Email To Task in Email Ribbon MS CRM 2011  post I have explained how to create ribbon button to copy email into task, in this post I am providing code to create task entity record through rest from email.

function ConverToTask() {
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();

    var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc;
    var task = new Object();

    if (Xrm.Page.getAttribute("subject).getValue()!=null)
            task.Subject = Xrm.Page.getAttribute("subject").getValue();
            if (Xrm.Page.getAttribute("regardingobjectid").getValue() != null) {
                var Regarding = Xrm.Page.getAttribute("regardingobjectid").getValue();
                task.RegardingObjectId = {
                    Id: Regarding[0].id,
                    LogicalName: Regarding[0].typename,
                    Name: Regarding[0].name
                };
            }
            var Task = this.parent.JSON.stringify(task);
            var CreateRequest = new XMLHttpRequest(); CreateRequest.open("POST", ODataPath + "/TaskSet", false); CreateRequest.setRequestHeader("Accept", "application/json"); CreateRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8"); CreateRequest.send(Task);
            if (CreateRequest.readyState == 4 /* complete */ ) {
                if (CreateRequest.status == 201) {
                    var retrievedRecords = this.parent.JSON.parse(CreateRequest.responseText).d;
                    var ID = retrievedRecords.ActivityId;
                    window.open(serverUrl + "/userdefined/edit.aspx?etc=4212&id=" + ID); //configure URL and open new window
                }
            }
        }

Enjoy !!!

Leave a Reply

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