Navigating the Lookup Labyrinth: Getting Related Record Information in Model-Driven App Forms

AJ Zafar

AJ Zafar

Solution Architect

Hey there, Power App adventurers! Today, we’re going to explore how to get related information from a record that a Lookup references. It can feel complex at first but with practice you will be able to add this method to your toolkit when building solutions.

If you are looking to just get the values of fields from the current record/form, I covered how to get data from different field types in my previous blog post.

The Power of Lookup Fields

Lookup fields in Power Apps are more than mere links between records; they are bridges to a wealth of information that can significantly enhance your app’s functionality. But how do we tap into this potential? The answer lies in understanding how to fetch related data efficiently when extending with JavaScript Webresources.

Fetching Basic Details from a Lookup Field

Before we dive into the complexities of select and expand, let’s start with the basics. Here’s how you can get the ID and name of a related record from a lookup field:

				
					function getBasicLookupDetails(executionContext) {
    const formContext = executionContext.getFormContext();
    let lookupField = formContext.getAttribute("yourLookupFieldName").getValue();

    if (lookupField) {
        let relatedRecordId = lookupField[0].id; // The GUID of the related record
        let relatedRecordName = lookupField[0].name; // The name of the related record
        // You can now use these details as needed
    }
}
				
			

Understanding Xrm.WebApi.retrieveRecord

Before diving deeper, it’s essential to understand Xrm.WebApi.retrieveRecord. This method is a part of the Web API, enabling operations against Dataverse. It’s used for retrieving a single record from an entity, requiring three parameters: the entity name, the record ID, and optional query options for data control. This method is crucial for fetching detailed information from related records. More detail on it can be found in the documentation: retrieveRecord (Client API reference) in model-driven apps – Power Apps | Microsoft Learn

Using select and expand to Retrieve Extended Information

To truly harness the power of lookup fields, we need to dive deeper, using OData’s select and expand queries with the Web API.

The select Query:

The select query allows you to specify which attributes of the related record you want to retrieve. This is particularly useful for performance optimization, as it limits the data returned to only what is necessary.

The expand Query:

The expand query takes it a step further, enabling you to fetch related records. This is where things get really exciting!

Putting It All Together

Now, let’s combine these concepts to retrieve detailed information from a related record:

				
					function getRelatedRecordDetails(executionContext) {
    const formContext = executionContext.getFormContext();
    let lookupField = formContext.getAttribute("yourLookupFieldName").getValue();

    if (lookupField) {
        let relatedRecordId = lookupField[0].id.replace('{', '').replace('}', '');
        let entityName = "relatedEntityName"; // Replace with the entity name of the related record

        Xrm.WebApi.retrieveRecord(entityName, relatedRecordId, "?$select=fieldName1,fieldName2").then(
            function (record) {
                // Access specific fields here
                let field1Value = record["fieldName1"];
                let field2Value = record["fieldName2"];
                // Handle the retrieved data as needed
            },
            function (error) {
                console.error("Error: " + error.message);
                // Error handling
            }
        );
    }
}
				
			

Deep-Dive with expand

When you want to pull data from a record related to your related record, expand comes into play. Here’s an example:
				
					function getExpandedRelatedRecordDetails(executionContext) {
    const formContext = executionContext.getFormContext();
    let lookupField = formContext.getAttribute("yourLookupFieldName").getValue();

    if (lookupField) {
        let relatedRecordId = lookupField[0].id.replace('{', '').replace('}', '');
        let entityName = "entityNameOfLookupField"; // Replace with the entity name for the lookup field

        let expandQuery = "?$expand=lookupFieldName($select=field1,field2)";
        // Replace 'lookupFieldName' with the logical name of your lookup field
        // 'field1', 'field2' are fields you want to retrieve from the related entity

        Xrm.WebApi.retrieveRecord(entityName, relatedRecordId, expandQuery).then(
            function (record) {
                let expandedRecord = record["lookupFieldName"];
                if (expandedRecord) {
                    let field1Value = expandedRecord.field1;
                    let field2Value = expandedRecord.field2;
                    // Process the retrieved data as needed
                }
            },
            function (error) {
                console.error("Error: " + error.message);
                // Handle errors appropriately
            }
        );
    }
}
				
			

Conclusion

Retrieving information from related records can significantly increase the customisations you can do with JavaScript Web resources with forms, creating more interconnected and dynamic experiences. Remember, the key is to keep your queries as specific and efficient as possible – retrieve only what you need.

With these skills in your arsenal, the labyrinth of lookup fields becomes a path to powerful possibilities!

Happy Power-Apping!

AJ Zafar

AJ Zafar

Solution Architect

Leave a Reply

Your email address will not be published. Required fields are marked *