+ Start a Discussion
Madhusudan Singh 19Madhusudan Singh 19 

Not able to navigate in lightning component used in visualforce

Hi All,

I have created a lightning component which I need to use in Visualforce. But whcih I try to navigate it gives error as could not use setParams of undefined in datable I am clicking on view details button which is calling handlerowaction function and there I am getting error because I am using  var navEvt = $A.get("e.force:navigateToSObject");
                navEvt.setParams({
                    "recordId": row.Id
                });

I did below things

1. Create Lightning Component
2. Create Lightning Application and calling Lighting Component
3. Created Visualforce Page and calling Lightning application

Below is my code

CaseEmails.cmp

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" 
                access="global" 
                controller="EmailCaseList">
    <aura:attribute name="ParentId" type="String"/>
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="recordId" type="String"/>
    
    <aura:attribute name="allData" type="List"/>
    <aura:attribute name="currentPageNumber" type="Integer" default="1"/>
    <aura:attribute name="pageSize" type="Integer" default="10"/>
    <aura:attribute name="totalPages" type="Integer" default="false"/>
    <aura:attribute name="pageList" type="List" default="false"/>
    
    <!-- This attribute will hold the update records from data table-->
    <aura:attribute name="updatedRecord" type="Object[]" />
    
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
        <lightning:workspaceAPI aura:id="workspace" />

    <!-- You must define keyField as 'Id' to save the record back in Salesforce
 'onsave' attribute will executed when user clicks on save button -->
    
    <lightning:layout multipleRows="true" horizontalAlign="center">
        <div style="height: 300px">
                <lightning:datatable
                                     aura:id="emailDataTable"
                                     columns="{! v.columns }"
                                     data="{! v.data }"
                                     keyField="Id"
                                     hideCheckboxColumn="true"
                                     onrowaction="{! c.handleRowAction }"/>
        </div>
        <lightning:layoutItem padding="around-small" flexibility="auto">
            <lightning:button label="First" iconName="utility:left" iconPosition="left"
                              onclick="{!c.onFirst}" disabled="{! v.currentPageNumber == 1}"/>
            <lightning:button iconName="utility:chevronleft" iconPosition="left"
                              onclick="{!c.onPrev}" disabled="{! v.currentPageNumber == 1}"/>
            <lightning:button iconName="utility:chevronright" iconPosition="right" 
                              disabled="{! v.currentPageNumber == v.totalPages}" onclick="{!c.onNext}"/>
            <lightning:button label="Last" iconName="utility:right" iconPosition="right" 
                              disabled="{! v.currentPageNumber == v.totalPages}" onclick="{!c.onLast}"/>
        </lightning:layoutItem>
    </lightning:layout>
    
</aura:component>
 


CaseEmailsController.js

({
    doInit : function(component, event, helper) {
        var actions = [
            { label: 'View Details', name: 'ViewDetails' }
        ],
            fetchData = {
                id : 'id.',
                Subject : 'Subject'
            };
        
        component.set('v.columns', [
            {label: 'Status', fieldName: 'Status', type: 'text'},
            {label: 'Subject Link', fieldName: 'SubjectHyperlink', type: "url", typeAttributes: {label: { fieldName: 'Subject' } , target: '_blank'}},
            {label: 'Email Address', fieldName: 'ToAddress', type: 'text'},
            {label: 'Message Date', fieldName: 'MessageDate', type: 'text'},
            {type: 'action', typeAttributes: { rowActions: actions} }
        ]);
        
        helper.getEmails(component, helper);

    },
    

    
    onNext : function(component, event, helper) {        
        var pageNumber = component.get("v.currentPageNumber");
        component.set("v.currentPageNumber", pageNumber+1);
        helper.buildData(component, helper);
    },
    
    onPrev : function(component, event, helper) {        
        var pageNumber = component.get("v.currentPageNumber");
        component.set("v.currentPageNumber", pageNumber-1);
        helper.buildData(component, helper);
    },
    
    onFirst : function(component, event, helper) {        
        component.set("v.currentPageNumber", 1);
        helper.buildData(component, helper);
    },
    
    onLast : function(component, event, helper) {        
        component.set("v.currentPageNumber", component.get("v.totalPages"));
        helper.buildData(component, helper);
    },
    
    handleRowAction: function(component, event, helper) {
        var action = event.getParam('action');
        var row = event.getParam('row');
        
        switch (action.name) {
            case 'ViewDetails':
                var navEvt = $A.get("e.force:navigateToSObject");
                navEvt.setParams({
                    "recordId": row.Id
                });
                navEvt.fire();
                break;
            
        }
    }
    
})
 



CaseEmailsHelper.js

({
    getEmails : function(component, helper) {
        var action = component.get("c.getLimitedEmails");
        action.setParams({
            caseId: component.get("v.ParentId")
        });
        action.setStorable();
        action.setCallback(this,function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
       var records =response.getReturnValue();
                console.log(records);
                records.forEach(function(record) {
                    if(record.Subject==null )
                          record.Subject='-'; 
                    record.SubjectHyperlink = '/'+record.Id; 
  
                    console.log(record.SubjectHyperlink);
                                }); 
                console.log('Response Time: '+((new Date().getTime())-requestInitiatedTime));
               component.set("v.totalPages", Math.ceil(response.getReturnValue().length/component.get("v.pageSize")));
                component.set("v.allData", records);
               component.set("v.currentPageNumber",1);
                helper.buildData(component, helper);
            }

        });
        var requestInitiatedTime = new Date().getTime();
        $A.enqueueAction(action);
    },
    
    
    /*
     * this function will build table data
     * based on current page selection
     * */
    buildData : function(component, helper) {
        var data = [];
        var pageNumber = component.get("v.currentPageNumber");
        var pageSize = component.get("v.pageSize");
        var allData = component.get("v.allData");
        var x = (pageNumber-1)*pageSize;
        
        //creating data-table data
        for(; x<=(pageNumber)*pageSize; x++){
            if(allData[x]){
                data.push(allData[x]);
            }
        }
        component.set("v.data", data);
    },
 })

Create LightningoutApp

<aura:application extends="ltng:outApp" >
    <aura:dependency resource="c:CaseEmails"/>
    <aura:dependency resource="markup://force:*" type="EVENT"/>
</aura:application>

Calling in visualforce page

<apex:page standardController="Case" showHeader="false" showChat="false" sidebar="false" docType="html-5.0">
    <apex:includeLightning />
   
    <div id="LcDisplayId"></div> 
    
 <script>
      
    $Lightning.use("c:CaseEmailsApp", function() {
    $Lightning.createComponent("c:CaseEmails",
    { 
      ParentId : "5004B000007f987" 	},
   "LcDisplayId",
    function(component) {
        
    });
 });
 </script>
</apex:page>
Raj VakatiRaj Vakati
You row action looks good for me and can you cofime me below points pls 
  1. Does your row action is wokring on lIghtning?
  2. Where you are using this VF page?

Try this 
 
<aura:application extends="ltng:outApp" >
    <aura:dependency resource="c:CaseEmails"/>
 <aura:dependency resource="markup://force:navigateToSObject" type="EVENT"/>
</aura:application>

 
Madhusudan Singh 19Madhusudan Singh 19
no it is still not working
Raj VakatiRaj Vakati
Does your row action is wokring on lIghtning?
Where you are using this VF page?
Madhusudan Singh 19Madhusudan Singh 19
yes it works in lightning component but  not in VF
Raj VakatiRaj Vakati
Can you do me a small help .. i belive the issue is with force:navigateToSObject .. 

Can you add some console .log and see whether you are getting the record id or not 

 
handleRowAction: function(component, event, helper) {
        var action = event.getParam('action');
        var row = event.getParam('row');
        console.log('row '+row );
        switch (action.name) {
            case 'ViewDetails':
 console.log('row '+row.Id);
                var navEvt = $A.get("e.force:navigateToSObject");
                navEvt.setParams({
                    "recordId": row.Id
                });
                navEvt.fire();
                break;
            
        }
    }


 
Madhusudan Singh 19Madhusudan Singh 19
I am getting ID in I printed console.log(row.Id);
User-added image
Raj VakatiRaj Vakati
Looks like an issue with force:navigateToSObject ... 

Can you use force navigate to URL or Simple A tag and ses
Raj VakatiRaj Vakati
Did you tried with A tag 
Madhusudan Singh 19Madhusudan Singh 19
Anchor tag will work but it will refresh the page