Who Viewed Record Last Lightning Component

Posted on

Hi All,

In this article I will tell you how to create Lightning Component which shows list of users who viewed record.You can use this Lightning Component for any object whether it is a custom object or standard object.

This can be useful when trying to trace who last Viewed a record? There’s no way to do this in salesforce as of now.It would be great if you could see on a record if anyone has recently viewed it, so I thought to create this Component.

To implement this you have to do following things.
1) On any object you want to use this Lightning Component, create a new custom textarea(255) field called “Last Visited By“.
2) Set History Tracking on for this field.

When complete it will look like this.

Let’s walk through code.

LastVisitedController.apxc :

public with sharing class LastVisitedController{
    
    @AuraEnabled
    public static sObject getViewersList(String recordId, String objectName){
        System.debug('objectName = '+objectName +' recordId = '+recordId);
        
        String query = 'SELECT Id, Name, '+
                       '(Select OldValue, NewValue, Field From Histories Where Field = \'Last_Visited_By__c\' ORDER BY CreatedDate DESC) '+
                       'FROM '+objectName +' Where Id = \''+ recordId + '\' LIMIT 1' ;
        
        sObject obj = Database.Query(query);
        
        return obj;
    }
    
    @AuraEnabled
    public static void updateRecord(String recordId, String objectName){
        Datetime sdate = System.now();        //Format the datetime value to your locale        
        String sysTime = sdate.format('dd/MM/yyyy HH:mm');
    
        String query = 'SELECT Id, Name, Last_Visited_By__c '+
                        'FROM '+objectName +' Where Id = \''+ recordId + '\' LIMIT 1' ;
        
        sObject obj = Database.Query(query);
        obj.put('Last_Visited_By__c' , System.Userinfo.getFirstName() + ' '+ System.Userinfo.getLastName() +' '+ sysTime);
        update obj;
    }
    
}

The getViewersList method is used to return list of users who visited record recently. Method updateRecord is used to update “Last Visited By” field when a user visited record.

LastVisitedCmp.cmp :

<aura:component controller="LastVisitedController" implements="force:appHostable,force:hasRecordId,force:hasSObjectName,flexipage:availableForAllPageTypes">
    <ltng:require styles="/resource/SLDS/assets/styles/salesforce-lightning-design-system-vf.css"/>
    <!-- Atrribute Defination for Object Name -->
	<aura:attribute name="sObjectName" type="String"></aura:attribute>
    <!-- Atrribute Defination for Record Id -->
	<aura:attribute name="recordId" type="String"></aura:attribute>
    <!-- Atrribute Defination for Who visited -->
	<aura:attribute name="visitorsList" type="sObject"></aura:attribute>
    <!-- Event Handler for init Event-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"></aura:handler>
    <!--page header-->
    <div class="slds">
        <div class="slds-page-header">
            <div class="slds-grid">
                <div class="slds-col slds-has-flexi-truncate">
                    <div class="slds-media">
                        <div class="slds-media__body">
                            <div class="slds-grid">
                                <h1 class="slds-text-heading--medium slds-m-right--small slds-truncate slds-align-middle">Recently Visited By</h1>
                            </div>
                        </div>
                    </div>
                </div>
            </div>   
        </div>
    </div>
    <!--Container-->
    <div class="container" style="overflow-y:scroll;height:300px">
        <ul class="slds-list--vertical slds-has-cards">
            <aura:iteration items="{!v.visitorsList.Histories}" var="h">
                <li class="slds-list__item">
                    <div class="slds-tile slds-tile--board">
                        <div class="slds-tile__detail">
                            <p class="slds-text-heading--medium">{!h.NewValue}</p>
                        </div>
                    </div>
                </li>
            </aura:iteration>	
        </ul>
    </div>
</aura:component>

The force:appHostable interface indicates the component can be hosted in the Salesforce1 Mobile app.
The flexipage:availableForAllPageTypes interface indicates the component can be used in App Builder.
The force:hasRecordId interface indicates the current record Id should be injected in the component’s recordId attribute.
The force:hasSObjectName interface indicates the current sObjectName should be injected in the component’s sObjectName attribute.

When the component is instantiated on the page, the current record Id and sObject are automatically injected in the recordId and sObjectName attribute. You can then make calls to the server passing the recordId and sObjectName as a parameter to retrieve or save data for that specific record.

LastVisitedCmpController.js :

({
	doInit : function(component, event, helper) {
		helper.getViewerList(component);
	},
})

LastVisitedCmpHelper.js :

({
	getViewerList : function(component) {
		var action = component.get("c.getViewersList");
        action.setParams({
            "recordId" : component.get("v.recordId"),
            "objectName" : component.get("v.sObjectName")
        });
        action.setCallback(this, function(action) {
        	component.set("v.visitorsList",action.getReturnValue());
        });
        
        $A.enqueueAction(action);
	},
    updateRecord : function(component) {
		var action = component.get("c.updateRecord");
        action.setParams({
            "recordId" : component.get("v.recordId"),
            "objectName" : component.get("v.sObjectName")
        });
        $A.enqueueAction(action);
	},
})

LastVisitedCmpRenderer.js :

({
    afterRender : function(component,helper){
        this.superAfterRender();
        helper.updateRecord(component);
    }	
})

The afterRender will be called when Component render completly. It will call helper function which updates “Last Viewed By” field of current record in the background.

🙂

Advertisements

3 thoughts on “Who Viewed Record Last Lightning Component

    […] Source: Who Viewed Record Last Lightning Component […]

    Liked by 1 person

    […] Source: Who Viewed Record Last Lightning Component […]

    Like

    Amul Baranwal said:
    July 8, 2016 at 6:52 pm

    Anything for Tab in lightning.
    I am using this that i copied from LightningSystem Design..but tab click is not working


    Item One


    Item Two


    Item Three

    Item One Content
    Item Two Content
    Item Three Content

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s