Retrieving a Form ID by Table name and Form Name in Dynamics 365 Using JavaScript

 In Dynamics 365, each form associated with an entity has a unique identifier, or form ID, which is useful when customizing or integrating with external systems. This tutorial will guide you through creating a JavaScript function that retrieves a specific form ID based on the entity name and the name of the form.

JavaScript Function to Retrieve Form ID

Below is the JavaScript function that queries the Dynamics 365 Web API to find the form ID based on the entity's logical name and the specific form name:

async function getFormIdByName(entityName, formName) {
    // Define the query to fetch formid and name for the specified entity and form name
    const query = `/api/data/v9.0/systemforms?$select=formid,name&$filter=objecttypecode eq '${entityName}' and name eq '${formName}'`;

    try {
        // Execute the API call
        const response = await fetch(Xrm.Utility.getGlobalContext().getClientUrl() + query, {
            method: 'GET',
            headers: {
                'OData-MaxVersion': '4.0',
                'OData-Version': '4.0',
                'Accept': 'application/json',
                'Content-Type': 'application/json; charset=utf-8',
                'Prefer': 'odata.include-annotations="*"'
            }
        });

        const data = await response.json();
        // Check if any forms are returned and log the form ID
        if (response.ok && data.value.length > 0) {
            console.log(`Form ID for '${formName}' in '${entityName}':`, data.value[0].formid);
            return data.value[0].formid;
        } else {
            console.log(`No form found with the name '${formName}' for the entity '${entityName}'.`);
            return null;
        }
    } catch (error) {
        console.error('Error fetching form ID:', error);
        return null;
    }
}

// Example usage
getFormIdByName('tri_programsession', 'Subgrid Bulk Edit Form');

Test Result:



How It Works:

  1. Query Construction: The function constructs a URL to query the system forms entity, selecting forms that match the given entity name and form name.
  2. API Call Execution: A fetch call is made to the Dynamics 365 Web API to retrieve the desired data.
  3. Result Handling: The function checks the API response, retrieves the form ID from the result, and logs it. It also handles errors and cases where no matching form is found.

Conclusion

This function provides a straightforward and efficient method to retrieve form IDs in Dynamics 365, facilitating deeper customization and integration capabilities. Whether you're a developer looking to automate processes or integrate Dynamics 365 with other applications, this script can help streamline your operations by providing quick access to form IDs based on specific criteria.

No comments:

Post a Comment