Thursday, December 19, 2024

JavaScript to automatically select a record in a subgrid when the form loads

JavaScript Subgrid Selection

Yesterday, someone from a WhatsApp group asked me to help on the following scenario:

“Any idea, when form loads, check form type if not new and has related record in subgrid then I need to select record on subgrid automatically. Any suggestion how we can use JavaScript?”

To achieve the requirement where a form loads, checks if the form type is not "new," and selects a related record in a subgrid if it exists, you can use JavaScript in your model-driven app. Here's how to implement this:

Step-by-Step Implementation

1. Setup Your Subgrid and Form

  • Ensure the subgrid is configured to display related records.
  • Identify the subgrid's name (you can find it in the form editor by selecting the subgrid and checking its properties, e.g., subgrid_name).

2. Add the JavaScript to Your Solution

async function onFormLoad(executionContext) {
    // Get form context
    const formContext = executionContext.getFormContext();

    // Check if form type is not "new"
    if (formContext.ui.getFormType() !== 1) { // 1 = Create form (New)
        try {
            // Wait for the subgrid to load and get its rows
            const subgridRows = await waitForSubgridLoad(formContext, "subgrid_name");

            // If subgrid has rows, perform your logic
            if (subgridRows.length > 0) {
                // Example: Select the first record or fetch data from an API
                const firstRow = subgridRows[0];

                // Call an API or perform additional operations (example API call)
                const apiData = await fetchApiData(firstRow.getData().getEntity().getId());
                console.log("API Data:", apiData);

                // Select the row in the subgrid
                firstRow.setSelected(true);
            }
        } catch (error) {
            console.error("Error handling subgrid or API:", error);
        }
    }
}

// Wait for the subgrid to load
function waitForSubgridLoad(formContext, subgridName) {
    return new Promise((resolve, reject) => {
        const subgrid = formContext.getControl(subgridName);
        if (!subgrid) {
            reject(new Error(`Subgrid '${subgridName}' not found.`));
            return;
        }

        // Subgrid may not load immediately; wait for it to finish loading
        subgrid.addOnLoad(() => {
            try {
                const rows = subgrid.getGrid().getRows();
                resolve(rows);
            } catch (err) {
                reject(err);
            }
        });
    });
}

// Fetch data from an API (example function)
async function fetchApiData(recordId) {
    const apiUrl = `https://your-api-endpoint.com/data/${recordId}`; // Replace with your actual API endpoint
    const response = await fetch(apiUrl, {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer YOUR_ACCESS_TOKEN" // Replace with actual token if needed
        }
    });

    if (!response.ok) {
        throw new Error(`API request failed with status: ${response.status}`);
    }

    return response.json();
}

3. Add the JavaScript to Your Form

  • Upload the JavaScript file to your solution as a web resource.
  • Open the form editor for the entity.
  • Go to Form Properties > Events tab.
  • Add the web resource under the Form Load event.
  • Add the function onFormLoad and ensure you pass the executionContext parameter.

Key Notes:

  1. Custom Selection Logic:
    • If you want to select a specific record based on certain criteria, you can loop through the rows collection and match the record based on your conditions:
      rows.forEach(function (row) {
          var data = row.getData();
          var entity = data.getEntity();
          if (entity.getId() === "desired_record_id") {
              row.setSelected(true);
          }
      });

No comments:

Post a Comment

Power Automate Optimization: Filter Rows vs Trigger Conditions - When and Why to Use Each

Filter Rows vs Trigger Conditions in Power Automate Filter Rows vs Trigger Conditions in Power Automate Why your flow...