Troubleshooting Error: Unknown Controller Action 'doInit' in Salesforce Lightning
- Get link
- X
- Other Apps
If you’ve encountered the error message:
Error: Unknown controller action 'doInit'
you’re not alone. This error commonly occurs when using the doInit
event in Salesforce Lightning components. Let’s explore why this happens and how to fix it.
Understanding the Error
The doInit
event is automatically fired when a Lightning application or component is initialized, prior to rendering. This means that when the page loads, the doInit
event is triggered and the system looks for the corresponding JavaScript function in the component's controller.
If the JavaScript controller does not contain a valid doInit
function, you will encounter the "Unknown controller action 'doInit'" error. This highlights the importance of ensuring that your controller is properly set up to handle this event.
Key Takeaway
Whenever you use the doInit
event in your Lightning component, it’s crucial to define a valid doInit
function in your JavaScript controller. Failing to do so will result in this error.
Example Code
Here’s an example of how you might set up a Lightning component with the doInit
event correctly:
<aura:component >
<aura:attribute name="Accounts" type="Account[]"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<div class="demo-only" style="width: 320px;">
<aura:iteration items="{!v.Accounts}" var="acc">
<ul class="slds-has-dividers_around-space">
<li class="slds-item">
<article class="slds-tile slds-tile_board">
<h3 class="slds-tile__title slds-truncate" title="Anypoint Connectors">
<a href="">{!acc.Name}</a>
</h3>
<div class="slds-tile__detail">
<p class="slds-text-heading_medium">{!acc.Amount}</p>
<p class="slds-truncate" title="Company One">
<a href="javascript:void(0);">Company One</a>
</p>
<p class="slds-truncate" title="Closing 9/30/2015">{!acc.CreatedDate}</p>
</div>
</article>
</li>
</ul>
</aura:iteration>
</div>
</aura:component>
Adding the doInit Function
To resolve the error, make sure to implement the doInit
function in your JavaScript controller. Here’s an example:
({
doInit: function(component, event, helper) {
// Logic to fetch account data and set it to component attribute
// For example:
var accounts = []; // Fetch your account data here
component.set("v.Accounts", accounts);
}
})
Conclusion
By ensuring that you have a valid doInit
function in your controller, you can avoid the "Unknown controller action 'doInit'" error. Always remember to verify that your component’s JavaScript logic is correctly implemented whenever you utilize the doInit
event. Happy coding!
Comments
Post a Comment