Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Suggested answer

How can I autoselect the next value for a Choice Field?

Posted on by 166

I have 2 Forms (of 2 entities: Backlog & Pipeline). Each of them has a subgrid for a third Entity called Cashflow where the relationships between Backlog and Cashflow and Pipeline and Cashflow are both (1:N)

Cashflow Records have a Choice field called Year (a list of Years: [2020, 2021, 2022, 2023, 2024, 2025).

Once the user clicks on the Cashflow Subgrid's 'Create New Cashflow' button, in the Backlog Main Form for example, if the subgrid contains 1 or more records the Year Field in the Quick Create Form that opens should be set to the next year choice automatically. Image:

NewYear.JPG

The JS code I am trying is below, launches OnLoad of the Cashflow Quick Create Form, and is correctly setting the next year in the Quick Create Form, but after saving the record and refreshing the page or after adding a new Cashflow record related to this Backlog the Year of the record in the Subgrid is incrementing alone and changing to a wrong value

function autoSelectNextYear(executionContext) {

    //Initiated Form Context.
    var formContext = executionContext.getFormContext();

    //get backlog Lookup value & pipeline Lookup value
    var backlog = formContext.getAttribute("cra1c_backlog_cashflow").getValue();
    var pipeline = formContext.getAttribute("cra1c_pipeline_cashflow").getValue();
    var optionSetValues = formContext.getAttribute("cra1c_yearchoice").getOptions();

    //Backlog Record (not Pipeline)
    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) {

                var countOfRelatedRecords = results.entities.length;

                if (countOfRelatedRecords !=0){
                    var followingYearId = results.entities[0]['cra1c_yearchoice'] 1;
                    formContext.getAttribute("cra1c_yearchoice").setValue(followingYearId);
                }
                else{
                    formContext.getAttribute("cra1c_yearchoice").setValue(null);
                }
            },
            
            function (error) {
                console.log(error.message);
            }
        )

        
    }
}

I've been stuck on this for a while so if anyone could please help I would greatly appreciate it. 

  • Suggested answer
    XM-22040801-0 Profile Picture
    XM-22040801-0 11 on at
    RE: How can I autoselect the next value for a Choice Field?

    Hello,

    The sorting is done on the Choice Field value, not on the label. Are you sure that the values are in the right order?

    I modified your code a bit and it works for me.
    I added some checks and $top and $select to get only the desired data.

    async function autoSelectNextYear(executionContext) {
        const formCtx = executionContext.getFormContext();
    
        const yearFieldName = "cra1c_yearchoice";
        const parentFieldName = "cra1c_backlog_cashflow";
        const entityName = "cra1c_mn_cashflow";
    
        const parent = formCtx.getAttribute(parentFieldName).getValue();
        const yearOptions = formCtx.getAttribute(yearFieldName).getOptions();
    
        if (parent == null) {
            Xrm.Navigation.openAlertDialog({ text: `${parentFieldName} field not set.` });
            return;
        }
    
        const parentId = parent[0].id;
    
        const result = await Xrm.WebApi.retrieveMultipleRecords(
            entityName,
            // Top and select to only retrieve wanted data
            `?$top=1&$select=${yearFieldName}&$filter=_${parentFieldName}_value eq ${parentId}&$orderby=${yearFieldName} desc`
        );
    
        const topYear = result.entities[0]?.[yearFieldName]; // Null if no result or if the year field is not set
    
        if (topYear != null) {
            const nextYear = topYear   1;
            const nextYearAvailable = yearOptions.some(option => option.value == nextYear);
    
            if (nextYearAvailable) {
                formCtx.getAttribute(yearFieldName).setValue(nextYear);
            }
            else {
                Xrm.Navigation.openAlertDialog({ text: `The next year (value: ${nextYear}) is not available.` });
            }
        }
        else {
            Xrm.Navigation.openAlertDialog({ text: "No previous year found. Please set the year manually." });
        }
    }

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!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,214 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans