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

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
<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>

 

  1. Create an apex class LastViewedByController. Below code is for LastViewedByController class
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;
       
    }
   
}

 

Here is the test class for the same.

@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();
    }
}

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.
<c:LastViewedComponent fldName="FieldAPINAME" ObjName="ObjectAPINAME" rendered="true" />

 

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: –

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

 

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

5 thoughts on “Setting-up-last-viewed-by-in-salesforce

  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!

Leave a Reply

Your email address will not be published. Required fields are marked *