1. 程式人生 > >Salesforce中實現Last Viewed By展示瀏覽資訊的幾點實施考慮

Salesforce中實現Last Viewed By展示瀏覽資訊的幾點實施考慮

案例背景】:
在早些時候客戶想要管理sf單子被瀏覽的資訊,比如被誰瀏覽,在什麼時候瀏覽,當時第一個想法就是使用cookie或者session之類的來實現,那使用session關掉視窗資訊就沒了,而cookie先拋開儲存容量的考慮,只要使用者清除了也沒了。那經過Google後找到如下方案。

方案細節】:
1. 建立一個Text(255)型別的欄位:Last_Viewed_By__c;
2. 為需要使用的物件建立一個visualforce元件,如:LastViewedComponent;

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

3. 建立一個Apex Controller,如LastViewedByController:

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(); 
        return LongDate;
    }
    
    public void updateField() {
        // Get the user info from the current user
        firstname = String.isEmpty(System.Userinfo.getFirstName()) ? '' : 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;
    }
    
}

4. 建立一個Visualforce Page,如LeadLastViewed.Page:

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

5. 最終效果:
有更新記錄許可權的使用者,點選檢視某條Lead記錄時,瀏覽資訊就會被記錄,表現形式是這個單子會被更新一下,即Last Modified值會變,如下: