【案例背景】:
在早些时候客户想要管理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. 将页面加进Page Layout即可;
6. 最终效果:
当有更新记录权限的用户,点击查看某条Lead记录时,浏览信息就会被记录,表现形式是这个单子会被更新一下,即Last Modified值会变,如下:
【缺陷性概述】:
1. 该方案只能看到上个浏览人的信息不能反映整个单子浏览人历史列表记录;
2. 需要浏览人对记录有Edit权限,因为需要更新单子;
3. 可能影响一些定时任务的执行。比如:使用Process Builder需要为该Lead安排Scheduled Action,当记录被创建或再次编辑满足条件定时发Welcome Email,这时如果这个单子被查看后记录会被更新,因此定时任务会重新评估,就会和预计计划有偏差。当然这种问题可能也与Process Builder的设计思路有关,其实我们知道workflow这点处理很好,如果我们将该Process Builder条件改为仅创建时才会基于创建后的1,2,3d...发welcome邮件,就能解决冲突。
【方案优化及改进后优点】:使用子对象来管理浏览历史
优点:
1. 可以管理浏览历史列表;
2. 可以分配子对象权限给对Lead有Read权限的所有人;
3. 创建子浏览历史记录不影响父记录后续扩展业务。