Skip to main content

Notifications

Microsoft Dynamics 365 | Integration, Dataverse...
Answered

Javascript to set email "To" field to case customer

Posted on by 45

Hello.  I am looking for some help with a JS web resource i am trying to create. My client wants the "To" field on the email form to be set to the Regarding Case customer. I understand that if they hit reply it will do this automatically but sometimes that reply "To" is a general support email and they end up sending a response to themselves. They were hoping this could just be set much like we did with the Case title for the subject line.  I have included that code below. I wasn't sure if it could be used as a base to update the "To".

  • lawilliams713 Profile Picture
    lawilliams713 45 on at
    RE: Javascript to set email "To" field to case customer

    Leah, you are a beautiful human! Once again you've nailed it! It worked perfectly and thank you so much for combining the two processes.

  • Verified answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Javascript to set email "To" field to case customer

    Hi lawilliams713,

    Here is my solution to solve the case.

    Step 1: Create a new web resource.

    pastedimage1648202248915v1.png

    Step 2: Enter JS code.

    JS code:

    function UpdateToField(executionContext) {

        debugger;

        var formContext = executionContext.getFormContext();

     

        var lookup = formContext.getAttribute("regardingobjectid").getValue();  // case lookup on email form

     

        if(lookup != null){

            var newid = lookup[0].id.slice(1, -1);

     

    var req = new XMLHttpRequest();

    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/incidents(" + newid + ")", 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.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

    req.setRequestHeader("Prefer", "odata.maxpagesize=50");

    req.onreadystatechange = function() {

        if (this.readyState === 4) {

            req.onreadystatechange = null;

            if (this.status === 200) {

                var result = JSON.parse(this.response);

                console.log(result);

                var title = result["title"];

                var ticketnumber = result["ticketnumber"];

                var subj = title + " - " + ticketnumber;

                var _customerid_value = result["_customerid_value"];//id

                var _customerid_value_formatted = result["_customerid_value@OData.Community.Display.V1.FormattedValue"];//name

                var _customerid_value_lookuplogicalname = result["_customerid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];//entity type

     

                if (_customerid_value != null) {

                    var value = new Array();

                    value[0] = new Object();

                    value[0].id = _customerid_value;

                    value[0].name = _customerid_value_formatted;

                    value[0].entityType = _customerid_value_lookuplogicalname;

                    formContext.getAttribute("to").setValue(value); //set the lookup value finally

                    formContext.getAttribute("subject").setValue(subj);

                }

                else

                alert("regarding is null");

            } else {

                Xrm.Utility.alertDialog(this.statusText);

            }

        }

    };

    req.send();

    }    

    }

    Step 3: Save and publish.

    Step 4: Navigate to Customization > Customize the system > Entity > Email > Forms.

    Step 5: Open the Email form, double-click Regarding, and then navigate to the Events tab.  Add the web resource you created.

     pastedimage1648202542632v2.png

    pastedimage1648202553862v3.png

    Step 6: Then save and publish.

    Test:

    pastedimage1648202523659v1.png

  • lawilliams713 Profile Picture
    lawilliams713 45 on at
    RE: Javascript to set email "To" field to case customer

    Hi Bipin,

    Thank you for your response. Is there any way you could put it all together for me? I've tried it a few ways based on your message but I haven't gotten it to work yet. I'm not a technical developer so trying to get this without exact guidance is a little out of my wheelhouse. I really appreciate your assistance!

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Javascript to set email "To" field to case customer

    Hello,

    You need to select Customer field in select query where you are fetching title & ticketnumber field. Then use below code to set TO field value

    function setToPartyList(fieldName, id, name, entityType) {

     var party = Xrm.Page.getAttribute(fieldName);

     // Create new array

     var partlist = new Array();

     partlist[0] = new Object();

     partlist[0].id = id;

     partlist[0].name = name;

     partlist[0].entityType = entityType;

     // Set array value

     party.setValue(partlist);

    };

    Field Name should be Email To field schema name

    ID - Customer record GUID

    Name - Customer Record Name

    entityType - Custom Record Entity Type which is account I believe

    Please mark my answer verified if this is helpful!

    Regards,

    Bipin Kumar

    Follow my Blog: xrmdynamicscrm.wordpress.com/

  • lawilliams713 Profile Picture
    lawilliams713 45 on at
    RE: Javascript to set email "To" field to case customer

    The post submitted before I was finished. Below is the code I was referencing.

    function emailFromCase(executionContext)

    {

     var formContext = executionContext.getFormContext();

     var CREATEDON = 1;

     var formType =formContext.ui.getFormType();

     if (formType == CREATEDON)

       {

         regardingOnchange(executionContext);

       }

    }

    function regardingOnchange(executionContext)

    {

     var formContext = executionContext.getFormContext();

     if (formContext.data.entity.attributes.get("regardingobjectid").getValue() != null)

     {

       var regarding = formContext.data.entity.attributes.get("regardingobjectid").getValue()[0].entityType;

       var id = formContext.data.entity.attributes.get("regardingobjectid").getValue()[0].id;

       var guid = id.replace(/{/g, "").replace(/}/g, "");

       if (regarding != null && guid != null)

        {

          if (regarding == "incident")

          {

             getCaseDetails(executionContext,guid);

           }

        }

      }

    }

    function getCaseDetails(executionContext,recordId)

    {

    // alert(recordId);

    var formContext = executionContext.getFormContext();

    var serverUrl = formContext.context.getClientUrl();

    var result;

    var oDataEndpointUrl = serverUrl + "/api/data/v9.2/incidents?$select=title,ticketnumber&$filter=incidentid eq " + recordId + "";

    //alert(oDataEndpointUrl);

    var service = new XMLHttpRequest();

    service.open("GET", oDataEndpointUrl, true);

    service.setRequestHeader("OData-MaxVersion", "4.0");

    service.setRequestHeader("OData-Version", "4.0");

    service.setRequestHeader("Accept", "application/json");

    service.setRequestHeader("Content-Type", "application/json;charset=utf-8");

    service.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");

    service.setRequestHeader("Prefer", "odata.maxpagesize=50");

    service.onreadystatechange = function ()

     {

      if (service.readyState == 4)

       {

         service.onreadystatechange = null;

            if (service.status == 200)

           {

             var requestResults = JSON.parse(this.response);

             if (requestResults != null && requestResults.value.length > 0)

               {

                  for (var i = 0; i < requestResults.value.length; i++)

                   {

                    var caseName = requestResults.value[i]["title"];

                    var caseNumber = requestResults.value[i]["ticketnumber"];

                    var subj = caseName + " - " + caseNumber;

                   }

                //alert(subj);

               formContext.getAttribute("subject").setValue(subj);

              }

           }

       }

     }

    service.send();

    }

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,240 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,149 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans