web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Suggested Answer

Select competitor Populate field & another forms field

(0) ShareShare
ReportReport
Posted on by 340

Hello,

so I went to workplace and select opportunities and select one of the case from there (now I am in the case). However we want to close this case because we unfortunately we didn’t get it (close as lost).

AA4905F5_2D00_FF93_2D00_4949_2D00_A28E_2D00_1CC8E47CA488.png

A pop up appears and tells us we can select the reason for close as well as choose the competitor.

CC7B25A3_2D00_193D_2D00_41B6_2D00_BEDA_2D00_B1B2EED70A2E.png

When I select the competitor a drop down appears with many selection. Once I choose the competitor out of the list I just wanted what I choose to appear in another field on the form, competitor field to show up the selection in the field. The competitor field is already there. 

Then when I select the contact person of who we do business with in this form - 

the problem here is I don’t have a competitor field in this form. Nor do I have the option to select competitor field because it didn’t exist. Can I create a competitor field for this form. After creating this field, I wanted when we select the competitor to populate this field of the selection as well. 

It will be in the contact form of the particular contact.

what do you advise on how I do this ?

I have the same question (0)
  • Johnseito Profile Picture
    340 on at

    I do see that in the contact form of the particular contact we can create new fields. So I created a Competitor field.

    But how can I make it where someone in the opportunity form of the particular opportunity that when they close as lost and select the Competitor, their selection populate this particular contacts Competitor field ?

  • Suggested answer
    cloflyMao Profile Picture
    25,210 on at

    Hi John, 

    Background:

    Each time when we close an opportunity, it will generate an associated record with opportunityclose as its entity type. 

    1031.JPG

    This type of entity is not directly accessible so we should give specific parameters in URL to view them.

    8738.JPG

    There are some useful fields which could help us to achieve your requirement.

    Competitor: It saves competitor we selected in the close an opportunity popup.

    Regarding field: It will save its parent opportunity.(the closed)

    1374.JPG

    So we could build a custom javascript web resource to retrieve current opportunity's(closed) associated opportunitycase record and fetch its competitor field data to populate the closed opportunity's competitor's. 

    Solution:

    Pre. enable Change Tracking option for opportunityclose entity to allow us to retrieve its data.

    pastedimage1571634691541v1.png

    1. create a script type web resource and paste code below:

     

    function setCompetitor(executionContext) {
      var formContext = executionContext.getFormContext();
      var formType = formContext.ui.getFormType();
      // Check current opportunity is closed
      if (formType == 3 || formType == 4) {
        var opportunityid = formContext.data.entity.getId();
        opportunityid = opportunityid.replace('{', '').replace('}', '');
        var url = Xrm.Utility.getGlobalContext().getClientUrl();
        var req = new XMLHttpRequest();
        req.open(
          "GET",
          url   "/api/data/v9.1/opportunitycloses?$filter=_regardingobjectid_value eq "   opportunityid   "",
          false
        );
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Prefer", 'odata.include-annotations="*"');
        req.send();
        if (req.readyState === 4) {
          if (req.status === 200) {
            var results = JSON.parse(req.response);
            if (results.value[0]["_competitorid_value"] != null) {
              formContext.getAttribute("new_competitor").setValue(
              [{
                  id: results.value[0]["_competitorid_value"],
                  name: results.value[0]["_competitorid_value@OData.Community.Display.V1.FormattedValue"],
                  entityType: results.value[0]["_competitorid_value@Microsoft.Dynamics.CRM.lookuplogicalname"]
              }]
              );
            }
          } else {
            var alertStrings = { confirmButtonLabel: "Close", text: JSON.parse(req.response).error, title: "Error occured" };
            var alertOptions = { height: 150, width: 250 };
            Xrm.Navigation.openAlertDialog(alertStrings, alertOptions).then(
              function success(result) {
                console.log("Closed");
              },
              function(error) {
                console.log(error.message);
              }
            );
          }
        }
      }
    }

    2. add its to formOnload event to Opportunity form

    8004.JPG

    3. enable pass execution context .. option

    1805.JPG

    4. After we save the popup form, and click refresh button(because we've updated data), the competitor of the current closed opportunity will be populated.(result based on my previous screenshot)

    17225.JPG

    Hope it helps.

    Regards,

    Clofly

  • Johnseito Profile Picture
    340 on at

    I did just what you said and posted. It didn’t work.

    I copied your code/function into notepad++, saved it as myFunction.js. Then I went to setting, customization and customize the system, go to web resources, click on New, enter name as myFunction, type as js, and uploaded the file.

    Then I click on Opportunity Close entity, click on Forms, click on Opportunity Close name of the form, click on Form Properties, on top Form Libraries I click Add, I look for new_myFunction and added it.

    In the bottom Event Handlers with Control as Form and Event as OnLoad I click Add, with Library as new_myFunction I added function setCompetitor click Ok and save and publish.

    I went to the opportunity, reopen it and then click on close as lost, the close opportunity pop up, I select the competitor and click Ok.

    I refresh the browser and go back to the same opportunity and the competitor field is not fill with the selection for that particular opportunity.

    Please not that in the form I created the competitor field and put it there and it’s name as new_competitor.

    I don’t know why when someone make the selection of competitor the  competitor field is not fill ?

    Hope you can follow my message.

  • cloflyMao Profile Picture
    25,210 on at

    Hi John,

    Sorry for that I missed a very important thing:

    In each time we close an opportunity, an opportunity close record will be generated, 

    thus the issue is caused by two factors: process above and my query filter;

    while for my filter, I just retrieved opportunity close records that have same regarding opportunity;

    if we close an opportunity multiple time, then multiple opportunity close records will be created and my original query always retrieve the opportunity close record that the first time we close opportunity.

    So to fix the issue, please replace req.open with code below:

        req.open(
          "GET",
          url   "/api/data/v9.1/opportunitycloses?$filter=_regardingobjectid_value eq "   opportunityid   " and statecode eq 1",
          false
        );

    There is another background process: only the latest opportunity close record will be active while the other previous records will be set to inactive.

    the additional filter and statecode eq 1 will only retrieve the most recent record.

    Please change the original code,

    now it will works for both situations:

    1. first time close 

    2. reopen and close again.

    Regards,

    Clofly

  • Johnseito Profile Picture
    340 on at

    Thanks for adding that piece. I think it can be very handy. But even after I follow your first example and the second example, I still don’t have the competitor field fill with the selected competitor after close the opportunity. What am I missing or doing wrong ?

    B570F4BD_2D00_D7D0_2D00_4D3E_2D00_A9BD_2D00_434961573E64.png

  • cloflyMao Profile Picture
    25,210 on at

    Hi John,

    Let us make trouble shooting below:

    1. make sure the form you're viewing is same as the form that you've added javascript.

    (Mine is Opportunity Main Form) 

    pastedimage1572323506506v1.png

    2. make sure you have enabled the Pass execution.. option

    pastedimage1572323600830v2.png

    3, make sure for formContext.getAttribute("new_competitor") that its name field for your Competitor field on form.

    pastedimage1572324313229v4.png 

    If 1 and 2 and 3 are all ok, it would works as expect; If above steps still not work, please read following:

    4. add a debugger at beginning part of setCompetitor(executionContext)

    pastedimage1572323745455v3.png

    then 4.1 open browser developer tool (F12, I took chrome as example), and open your opportunity form with a closed opportunity,

    you will enter debug mode, it will check whether there is anything wrong in code,

    4.2 by click F10, you can execute function step by step,

    4.3 if everything is ok, you could stay your cursor on results variable to see whether your latest competitor name has been included in _competitor_value@OData.Community.Display.V1.FormattedValue attribute.

    4.4 and finally you'll go to formContext.getAttribute("new_competitor").setValue();

    in other word, if there was no error in code, every variable will display their value druring the process.

    4265.JPG

    (in my screenshot, I inserted a break point at function beginning for debug, which could be equivalent to add a debugger code)

    If you met any error in debugging mode, please share me a sceenshot with error if possible, thanks.

    Regards,

    Clofly

  • cloflyMao Profile Picture
    25,210 on at

    Hi John,

    Besides my step 1, 2, 3, 4,

    You should also click refresh the form to see update.

    Regards,

    Clofly

  • cloflyMao Profile Picture
    25,210 on at

    Hi John,

    Please let me know how it is going.

    If step 1, 2, 3 both not works, can you jump into setCompetitor function ?

    Regards,

    Clofly

  • Johnseito Profile Picture
    340 on at

    Thanks for your update. I am looking into it now.

  • Johnseito Profile Picture
    340 on at

    Upon troubleshooting for #3 I am not sure where you get formContext.getAttribute.

    How do I go there to see if I have or set what you have set ?

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
Martin Dráb Profile Picture

Martin Dráb 47 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 38 Super User 2025 Season 2

#3
Pallavi Phade Profile Picture

Pallavi Phade 32

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans