Skip to main content

Notifications

Announcements

No record found.

Dynamics 365 Community / Forums / Sales forum / Is it Possible to sele...
Sales forum
Answered

Is it Possible to select an option for a choice field with Javascript?

Posted on by 146

Hello, 

I have a Quick Create Form for an entity called `Cashflow` that launches from a Subgrid of an entity called 'Backlog' to create multiple cashflow records related to that backlog. The Cashflow's Quick Create Form contains 3 fields: Backlog Name, Backlog Amount, and Year (dropdown choice field of a list of years).

 Once the Cashflow's Quick Create Form loads, if there are no cashflow records related to the backlog in the subgrid, the Year field would be empty for the user to enter the first record. (Image Example below):

empty-quick-create-cashflow.png

Else if there are related records, I'm trying to have the Year Field to have as preselected the year after the latest in the subgrid. Example In the image below, Cashflow 1 is for year 2020, Cashflow 2 is for the year 2021, and if I create a new cashflow (from subgrid quick create) Cashflow 3 should be for the year 2022. Is there a way to accomplish this with JS?

with-records.png

Categories:
  • Verified answer
    a33ik Profile Picture
    a33ik 84,321 Most Valuable Professional on at
    RE: Is it Possible to select an option for a choice field with Javascript?

    Hello,

    I would recommend checking if you have any background process (workflow, plugin, powerautomate flow) that does that update.

  • Joseph Nasr Profile Picture
    Joseph Nasr 146 on at
    RE: Is it Possible to select an option for a choice field with Javascript?

    I was reading about the line of code you recommended and that it is to check that the code only runs if the form is a create form.

    I added the code you recommended as shown below, but the problem is still after refreshing the Main Form that contains the subgrid, the Year field for the record created in that subgrid is still incrementing by1. (Setting the year to 2020 while creating the record, it still becomes 2021 after saving the record from the Quick Create Form and after refreshing the page).

    if (formContext.ui.getFormType()!==1){
            return;
        } else {
            if (backlog != null && pipeline == null) {
                var backlogId = backlog[0].id;
    
                //Get all cashflows related to this backlog, and sort them by Year in descending order
                Xrm.WebApi.retrieveMultipleRecords("cra1c_mn_cashflow", "?$filter=_cra1c_backlog_cashflow_value eq "   backlogId   "&$orderby=cra1c_yearchoice desc").then(
                    function success(results) {
    
                        //count of cashflow records related to this backlog
                        var countOfRelatedRecords = results.entities.length;
    
                        //If it's not the first record, get and set the next year option
                        if (countOfRelatedRecords > 0) {
                            var currentLatestYearId = results.entities[0]['cra1c_yearchoice'];
                            var nextYearId = currentLatestYearId  = 1;
                            formContext.getAttribute("cra1c_yearchoice").setValue(nextYearId);
                        }
                    },
                    function (error) {
                        console.log(error.message);
                    }
                )
            }
        }

    At this point I went to form properties and removed the web resource as it is, but still creating a new record in the subgrid is still incrementing by 1 after refresh.

    It is very strange I can't understand why as there are no other web resources triggering onLoad of this Form!

  • Suggested answer
    a33ik Profile Picture
    a33ik 84,321 Most Valuable Professional on at
    RE: Is it Possible to select an option for a choice field with Javascript?

    Hello,

    I would recommend adding the following code to avoid the code being triggered on the existing records:

    var formContext = executionContext.getFormContext();

    if (formContext.ui.getFormType() !== 1){

    return;

    }

  • Joseph Nasr Profile Picture
    Joseph Nasr 146 on at
    RE: Is it Possible to select an option for a choice field with Javascript?

    So I managed to write the JS code below and it is working in terms of preselecting the next year choice in the Year Field. But the issue is that after saving the new record (and refreshing the page if needed), the value selected is always getting incremented by 1 (after save).

    Ex: If I had an existing cashflow record: Cashflow 1 - Year 2020, when creating Cashflow 2 - Year is getting populated with 2021 correctly. But after saving, 2020 changes to 2021, and the 2021 of the newly created record (second cashflow record) changes to 2022. 

    What could be triggering this? (Note: I used Xrm.WebApi.retrieveMultipleRecords to retrieve the related records and sorted them in descending order so the first record [0 has the latest Year)

    Code:

    function autoSelectNextYear(executionContext) {
    
        //Initiated Form Context.
        var formContext = executionContext.getFormContext();
    
        //get backlog Lookup value & pipeline Lookup value & set of year options
        var backlog = formContext.getAttribute("cra1c_backlog_cashflow").getValue();
        var pipeline = formContext.getAttribute("cra1c_pipeline_cashflow").getValue();
        var optionSetValues = formContext.getAttribute("cra1c_yearchoice").getOptions();
    
        if (backlog != null && pipeline == null) {
            var backlogId = backlog[0].id;
    
            //Get all cashflows related to this backlog, and sort them by Year in descending order
            Xrm.WebApi.retrieveMultipleRecords("cra1c_mn_cashflow", "?$filter=_cra1c_backlog_cashflow_value eq "   backlogId   "&$orderby=cra1c_yearchoice desc").then(
                function success(results) {
    
                    //count of cashflow records related to this backlog
                    var countOfRelatedRecords = results.entities.length;
    
                    //If it's not the first record, get and set the next year option
                    if (countOfRelatedRecords > 0) {
                        var currentLatestYearId = results.entities[0]['cra1c_yearchoice'];
                        var nextYearId = currentLatestYearId  = 1;
                        formContext.getAttribute("cra1c_yearchoice").setValue(nextYearId);
                    }
                },
                function (error) {
                    console.log(error.message);
                }
            )
        }
    }
      

  • Suggested answer
    a33ik Profile Picture
    a33ik 84,321 Most Valuable Professional on at
    RE: Is it Possible to select an option for a choice field with Javascript?

    Hello,

    That's doable.

    1. Get the Id of the parent record either by placing the lookup field on the quick create form and get it using formContext.getAttribute("parent lookup field").getValue() or using the approach I described here - butenko.pro/.../

    2. Build a query to query the "Cashflow" records that are related to the parent. My recommendation is to use Dataverse Rest Builder tool - github.com/.../DRB.

    3. Loop through the existing records and get the latest one. Use the next one to populate your dropdown.

    Good luck and feel free to update the thread if you have any questions.

Helpful resources

Quick Links

Dynamics 365 Community Update – Sep 16th

Welcome to the next edition of the Community Platform Update. This is a weekly…

Announcing Our 2024 Season 2 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 290,339 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 228,177 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,148

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans