Skip to main content

💡 X++ Tip: Keep the Same Record Selected After Refresh in a Form or Data Source

 When you refresh a form data source in Dynamics AX or Dynamics 365 for Finance and Operations, the current selection is often lost — the cursor jumps back to the first record. This can be frustrating, especially if you want the user to remain on the same record after an update or refresh. Here’s a simple and reliable way to restore the cursor to the same record after the data source is refreshed. 🧩 Scenario Suppose we have a form displaying records from MyTable . When we refresh the data source — for example, after updating a field or calling executeQuery() — we want the form to return to the same record the user was viewing before the refresh. ✅ Solution: Use ds.cursor() We can achieve this using a record buffer and the cursor() method of the data source. public void refreshDataSource() { MyTable myTableRec; // buffer to store current record // Store the current record myTableRec = MyTable_ds.cursor(); // Refresh the data source MyTable_ds.r...

Calculating Managed Cost Site-Wise in Dynamics 365 Finance and Operations using X++


    /**

     * Calculate the managed cost for a given item and site.

     * 

     * @param _itemId The ItemId for which the managed cost is to be calculated.

     * @param _siteId The SiteId for which the managed cost is to be filtered.

     * 

     * @return The calculated managed cost for the given site.

     */

    private real calculateManagedCostBySite(ItemId _itemId, InventSiteId _siteId)

    {

        Query                        query;

        QueryRun                     queryRun;

        QueryBuildDataSource         inventSumDS, inventDimDS, inventTableDS;

        InventSum                    inventSum;

        InventDim                    inventDim;

        

        real                         totalPostedValue = 0;

        real                         totalPostedQty = 0;

        real                         managedCost = 0;

        boolean                      hasRecords = false;  // To check if the query has any results


        // Initialize query

        query = new Query();


        // Add InventSum as the main data source

        inventSumDS = query.addDataSource(tableNum(InventSum));

        inventSumDS.addSelectionField(fieldNum(InventSum, PostedQty), SelectionField::Sum);

        inventSumDS.addSelectionField(fieldNum(InventSum, PostedValue), SelectionField::Sum);

        

        // Group by fields

        inventSumDS.addGroupByField(fieldNum(InventSum, ItemId));

        inventSumDS.addGroupByField(fieldNum(InventSum, InventDimId));


        // Join InventDim table and group by site (InventSiteId)

        inventDimDS = inventSumDS.addDataSource(tableNum(InventDim));

        inventDimDS.relations(true);

        inventDimDS.joinMode(JoinMode::InnerJoin);

        inventDimDS.addLink(fieldNum(InventSum, InventDimId), fieldNum(InventDim, InventDimId));

        inventDimDS.addSelectionField(fieldNum(InventDim, InventSiteId));

        inventDimDS.addGroupByField(fieldNum(InventDim, InventSiteId));


        // Filter by the given SiteId

        if (_siteId)

        {

            inventDimDS.addRange(fieldNum(InventDim, InventSiteId)).value(queryValue(_siteId));

        }


        // Join InventTable table

        inventTableDS = inventSumDS.addDataSource(tableNum(InventTable));

        inventTableDS.relations(true);

        inventTableDS.joinMode(JoinMode::InnerJoin);

        inventTableDS.addLink(fieldNum(InventSum, ItemId), fieldNum(InventTable, ItemId));


        // Add range for the specified item

        inventSumDS.addRange(fieldNum(InventSum, ItemId)).value(queryValue(_itemId));


        // Execute query and calculate site-wise average cost

        queryRun = new QueryRun(query);


        // Loop over query results but only update for the correct site and avoid multiple updates

        while (queryRun.next())

        {

            inventSum = queryRun.get(tableNum(InventSum));

            inventDim = queryRun.get(tableNum(InventDim));


            // If the record matches the site

            if (inventDim.InventSiteId == _siteId)

            {

                totalPostedQty = inventSum.PostedQty;

                totalPostedValue = inventSum.PostedValue;


                // Avoid division by zero

                if (totalPostedQty != 0)

                {

                    managedCost = totalPostedValue / totalPostedQty;

                    hasRecords = true;

                }

            }

        }


        // If no records found, return 0

        if (!hasRecords)

        {

            info(strFmt("No records found for Site: %1", _siteId));

            return 0;

        }

        

        info(strFmt("Site: %1, Managed Cost: %2", _siteId, managedCost));

        return managedCost;

    }

}


Comments

Popular posts from this blog

How to Refresh a Form or Data Source in D365FO Using X++

  Introduction In Microsoft Dynamics 365 Finance & Operations (D365FO), refreshing the form after an action (like inserting, updating, or deleting a record) is essential for keeping the UI updated with the latest data. In this blog, we’ll explore two ways to refresh the form in X++: ✅ Refreshing the entire form using taskRefresh ✅ Refreshing a specific data source using research Let's dive into the best practices for implementing these refresh methods! 🔄 Refreshing the Entire Form If you need to refresh the whole form , use the taskRefresh method. This method is useful when multiple data sources are involved, and you want to reload everything. 📌 X++ Code for Full Form Refresh public void refreshForm() {     // Get the current form instance     FormRun formRun = this.formRun();     // Check if formRun is valid before refreshing     if (formRun)     {         info("Refreshing the form...");     ...

How to Open a Form with Filtered Data Using a Button in X++ – A Step-by-Step Guide

 In Dynamics 365 for Finance and Operations (D365FO), a common requirement is to open a form dynamically from another form and pass filtered data based on a specific condition. This functionality can enhance user experience by allowing them to interact with multiple forms seamlessly, while keeping the data relevant and focused. In this blog, we’ll explore how to implement such a solution using X++, where a user clicks a button on Form 1 (such as a list of sales orders), and based on a selected record, Form 2 (such as invoice details) opens with only the relevant filtered data. Scenario Overview Let’s assume the following scenario: Form 1 : Displays a list of sales orders, and each order has an OrderID , CustomerID , and OrderAmount . Form 2 : Displays details of invoices (from the InvoiceDetails table) that are linked to the selected OrderID from Form 1 . The goal is to click a button on Form 1 , pass the OrderID to Form 2 , and display only the relevant invoice records relate...

Sorting Data in X++ (D365FO) Grids Using Form Data Source Events

  Introduction : In Dynamics 365 Finance and Operations, form grids often display data retrieved from a table or query. However, the default sorting applied may not always align with business requirements. Customizing sorting behavior at runtime ensures that the grid data is presented in a meaningful order for users. This blog post demonstrates how to use the Initialized event of a form data source to apply custom sorting to a grid. We will sort the grid rows based on a specific field ( DisplayOrder ) in ascending order. Understanding the Code : Here’s the complete code snippet: --------------------------------------------------------------------------------------------------------------- [FormDataSourceEventHandler(formDataSourceStr(MyFormDataSource,  MyTable), FormDataSourceEventType::Initialized)] public static void MyFormDataSource_OnInitialized(FormDataSource sender, FormDataSourceEventArgs e) {     // It will clear if any other sorting is applied on the grid ...