Setting-up-last-viewed-by-in-salesforce

on

|

views

and

comments

Setting-up-last-viewed-by-in-salesforce

As Salesforce does not provide the standard functionality by which we can know which user last visited the record. To achieve this functionality, we need to develop the custom solution using apex and VF page.

Here, I had developed a solution that can be re-used for any custom/standard object. (You can say a generic VF page with the help of VF component).

Step1 – Create a Text(255) field on the Object on which you wanted to track the recent visit. For example, the Label of the field is “Last Viewed By“.

  1. Create VF component LastViewedComponent . Below is the code for LastViewedComponent VF component

[codesyntax lang=”xml” container=”div”]

<apex:component access="global" controller="LastViewedByController"  allowDML="true">
    
    <!-- Script to call the Apex method which will update the field -->
    <script>
       window.onload=function(){
         doInit();
       };
    </script>
    <apex:attribute name="ObjName" type="String" assignTo="{!objectName}" 
                    description="Object Name on which VF is developed" 
                    access="global" required="true" />
    
    <apex:attribute name="fldName" type="String" assignTo="{!fieldName}" 
                    description="Field API name where you need to show the Last Viewed By" 
                    access="global" required="true" />
    
    <apex:form >
        <apex:actionFunction name="doInit" action="{!updateField}" reRender=""/>
    </apex:form>
</apex:component>

[/codesyntax]

 

  1. Create an apex class LastViewedByController. Below code is for LastViewedByController class

[codesyntax lang=”java” container=”div”]

public class LastViewedByController{
    
    public Datetime cDT;
    public String LongDate;
    public String firstname;
    public String lastname;
    
    public static String objectName { get; set; }
    public static String fieldName { get; set; }
    public static String recordId { get; set; }
    
    public lastViewedByController(){
              
    }
    
    public String getLongDate() {
        cDT = System.now(); //Format the datetime value to your locale
        LongDate = cDT.format('dd/MM/yyyy HH:mm'); 
        return LongDate;
    }
    
    public void updateField() {
        // Get the user info from the current user
        firstname = System.Userinfo.getFirstName();
        lastname  = System.Userinfo.getLastName();
        recordId = ApexPages.CurrentPage().getParameters().get('id'); 
        String fieldQuery = 'Select Id, '+fieldName +' From '+objectName +' Where Id = '+'\''+recordId+'\'';
        //System.debug('#### Query  '+fieldQuery );
        sObject objectToUpdate = Database.Query(fieldQuery);
        
        objectToUpdate.put(fieldName, (firstname + ' ' + lastname + ', ' + getLongDate()));
        //System.debug('#### objectToUpdate '+objectToUpdate);
        update objectToUpdate;
        
    }
    
}

[/codesyntax]

 

Here is the test class for the same.

[codesyntax lang=”java” container=”div”]

@isTest
private class LastViewedByController_Test {
    @testSetup
    public static void generateTestData(){
        Account acc = new Account(Name = 'Last Viewed By');
        insert acc;
    }
    public static testMethod void updateField_Test(){
        Test.startTest();
        	Test.setCurrentPage(Page.LastViewedBy);
        	LastViewedByController.objectName = 'Account';
        	LastViewedByController.fieldName = 'Name';
        lastViewedByController contr = new lastViewedByController();
        List<Account> accList = new List<Account>([Select Id, Name From Account Where Name = 'Last Viewed By' LIMIT 1]);
        	ApexPages.currentPage().getParameters().put('id', accList[0].Id);
        //LastViewedByController.recordId = accList[0].Id;
        contr.updateField();
        Test.stopTest();
    }
}

[/codesyntax]

Step 2 – Create a VF page with standard Controller attribute and add the below VF component to your VF page. In the VF page use the Object API name for StandardController.

  • fldName: – Use Field API name for this attribute.
  • ObjName: – Use object API name for this as value.

[codesyntax lang=”xml” container=”div”]

<c:LastViewedComponent fldName="FieldAPINAME" ObjName="ObjectAPINAME" rendered="true" />

[/codesyntax]

 

For Example, you wanted to track the recent visit for Account Object and the Field API name is Last_Viewed_By__c then VF page will look like below: –

[codesyntax lang=”xml” container=”div”]

<apex:page standardController="Account" >
      <c:LastViewedComponent fldName="Last_Viewed_By__c" ObjName="Account" rendered="true" />
</apex:page>

[/codesyntax]

 

Step3 – Add VF page into the Page layout of the Object.

Step4 – Make the Field readonly at the Profile Level so that user can not enter any value manually.

 

Thanks for reading. Sharing is caring 🙂

If you have any query or suggestions please come up in the comment section with OR you can tweet me @cloudyamit

Amit Singh
Amit Singhhttps://www.pantherschools.com/
Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion
Share this

Leave a review

Excellent

SUBSCRIBE-US

Book a 1:1 Call

Must-read

How to Utilize Salesforce CLI sf (v2)

The Salesforce CLI is not just a tool; it’s the cornerstone of development on the Salesforce Platform. It’s your go-to for building, testing, deploying, and more. As one of the most important development tools in our ecosystem

Save the day of a Developer with Apex Log Analyzer

Table of Contents What is Apex Log Analyzer? Apex Log Analyzer, a tool designed with Salesforce developers in mind, is here to simplify and accelerate your...

Salesforce PodCast

Introduction Hey Everyone, Welcome to my podcast, the first-ever podcast in India for Salesforce professionals. Achievement We are happy to announce that we have been selected as Top...

Recent articles

More like this

7 COMMENTS

  1. This is great. I never thought of doing this but I think there would be some great use cases for it. Thank you for sharing!

  2. This field gets populated immediately once opening up the record. Is there a way to show who opened it prior to me and keep it like that. Or when it was first viewed/read by?

    I’m looking to see when an opportunity was first viewed/read by a user in a community when I send them an opportunity. I’d like to see when they viewed the opportunity record rather than it update every time the record is viewed.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5/5

Stuck in coding limbo?

Our courses unlock your tech potential