force:navigateToURL example in Salesforce Lightning

Apex Class:- "AccountListController"
public class AccountListController {
	@AuraEnabled
    public static List <Account> fetchAccts() {
        List<Account> lstacc= [ SELECT Id, Name, Industry FROM Account LIMIT 10 ];
        return lstacc;
    }
}
Component:- "AccountListComponent"
<aura:component controller="AccountListController" >
<aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
<aura:attribute name="acctList" type="List"/>

<table class="slds-table slds-table_bordered slds-table_cell-buffer">
<thead>
<tr class="slds-text-title_caps">
<th scope="col">
<div class="slds-truncate" title="Account Name">Account Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Account Name">Industry</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Action">Actions</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.acctList}" var="a">
<tr>
<td data-label="Account Name">
<div class="slds-truncate" title="">{!a.Name}</div>
</td>
<td data-label="Industry">
<div class="slds-truncate" title="">{!a.Industry}</div>
</td>
<td> 
<!--a class="slds-button slds-button_brand" id="{!a.Id}" href="{!'/'+a.Id}" target="blank">View</a-->
<button class="slds-button slds-button_brand" onclick="{!c.viewAccount}" id="{!a.Id}">View</button>
</td> 
</tr>
</aura:iteration>
</tbody>
</table>
</aura:component>
JS Controller
({
fetchAccounts : function(component, event, helper) {
var action = component.get("c.fetchAccts");
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
var accResp=response.getReturnValue();
component.set("v.acctList", accResp);
}
});
$A.enqueueAction(action);
},
viewAccount : function(component, event, helper) {
var viewRecordEvent = $A.get("e.force:navigateToURL");
if(viewRecordEvent){
viewRecordEvent.setParams({
"url": "/" + event.target.id
});
viewRecordEvent.fire();
}
else
{
//window.location.href = "/" + event.target.id
window.open("/" + event.target.id,'_blank')

}
}

})

Aura Application: AccountListAPP

<aura:application extends="force:slds" >
<c:AccountListComponent></c:AccountListComponent>
</aura:application>

OUTPUT:-

Leave a Reply