More importantly… I learned how to initialize Lightning Components from properties in an Apex Controller.
I wanted to display the detail page for a Contact in a lightning component. Essentially the equivalent of “<apex:detail>” tag. In Lightning, you can achieve this by using the “<force:recordView>” tag instead. What I learned is that the force:recordView tag doesn’t support asynchronous updates of its data. Meaning that when the element loads, it expects to have the “recordId” property already populated.
However, when the page first loads (without having the value passed into the component as a parameter), you need to initialize and query the data first. So the data isn’t available on load of the element, and you get an “Invalid Page” error.
You need to dynamically create the <force:recordView> element from the component’s controller.js file. Here’s some code showing how I did it:
Some things to note about the component view:
- aura:handler tag initiates a controller function, and passes in the entire state of the component, including the Apex Controller (that’s important in a moment)
Some things to note about the Apex Controller:
- @AuraEnabled tag must be set in order for Lightning components to access the method (also applies to properties)
- the method is static because Aura requires it (does not support class instances)
So lets take a look at what this is doing…
- When the component loads, the aura:handler tag calls the doInit function and passes in the component state.
- the “action” var is set to the Apex Controller’s “getContactId” method
- then we define what to do after that action completes:
- set the return value in an “id” var
- find our “contactRecord” div on the component view
- dynamically create a force:recordView component, and then set the body of our div to the resulting component output
- $A.enqueueAction kicks off the getContactId action
The end result is a few lines of code that render an entire detail page. And you can then control your output via standard page layouts in config (just like classic salesforce).
Not all Lightning components need this type of callback/dynamic create design pattern, however there are components that do. So be aware when designing.