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

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Suggested Answer

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

(0) ShareShare
ReportReport
Posted on by 183

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
    11 on at

    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

Season of Sharing Community Challenge Winners!

Congratulations to our community stars!

Women in Power Builds Momentum

Expanding mentorship, skilling, and AI innovation

Congratulations to the July Top 10 Community Leaders

These are the community rock stars!

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Syed Aqib Raza Profile Picture

Syed Aqib Raza 96

#2
11manish Profile Picture

11manish 90 Super User 2026 Season 2

#3
ParthPatel249 Profile Picture

ParthPatel249 80

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans