Tuesday, March 26, 2013

CRM 2011: Populate email From field with a specific queue in javascript

I had to automatically set a specific queue in From field of an email when the form loads. So I created a function that I call it an Onload of email form for this.  Note that I had extra checks (like email to be outgoing).

You need jquery and json2 scripts to be included on this form.
The code for GetServerUrl function you can find it other post of mine (or you can use your own method).

function PopulateFromAddressOnLoad() {

    var formType = Xrm.Page.ui.getFormType();
    var emailStatus = Xrm.Page.getAttribute("statecode").getValue();
    var emailDirection = Xrm.Page.getAttribute("directioncode").getValue();
 
    var defaultQueueEmail = "somequeueemails@email.com";

    if (formType == 1 || (formType == 2 && emailStatus == "Open")) {

        //check if it's outgoing
        if (emailDirection == "1") {

            $.ajax({
                type: "GET",
                async: false,
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: GetServerUrl() + "/xrmservices/2011/OrganizationData.svc/QueueSet?$select=Name,QueueId&$filter=EMailAddress eq '" + defaultQueueEmail + "'",
                beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
                success: function (data, textStatus, XmlHttpRequest) {

                    if (data != undefined && data.d != undefined && data.d.results[0] != undefined) {

                        var queue = data.d.results[0];

                        if (queue != null) {
                            var queueId = queue.QueueId;
                            var lookup = new Array();
                            var lookupItem = new Object();

                            lookupItem.id = queueId;
                            lookupItem.name = queue.Name;
                            lookupItem.typename = "queue";

                            lookup[0] = lookupItem;

                            Xrm.Page.getAttribute("from").setValue(lookup);

                        }
                    }
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed '); }
            });
        }
    }
}


No comments:

Post a Comment