由于Salesforce只支持根据条件动态选择审批分支,如果我们想进一步支持动态根据页面的某种条件选择审批人,Salesforce是不支持的。因此我们只能通过override salesforce审批类来实现,具体步骤如下:
0,以管理员身份新建立一个审批流为Opportunity(审批流名称和每个节点的名称我们从写时候时候需要用到)
1,添加一个名称为Submit for Approval By Neo 自定义按钮给Opportunity(由于我们要重写的是Opportunity的审批流)在Opportunity Object 中的 ‘Buttons, Links, and Actions’ 如下:
填完后填写js代码,由于我们想通过点击直接启动工作流,所以我们需要在这里通过js 调用webservice 类启动。代码如下:
<!--参数名区分大小写,对于跨层object直接在Object名后直接加参字段名即可-->
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")} var OppID='{!Opportunity.Id}'
var Comments = 'submited'
var OppSubmitter = '{!$User.Id}'
var result = sforce.apex.execute("OppApprovalProcess", "SubmitforApproval", {oppID:OppID,Comments:Comments,userID:OppSubmitter });
window.location.reload()
2,在这里我们看到我们需要调用OppApprovalProcess类下SubmitforApproval方法实现审批的提交,下面就是调用提交的代码:(里面还还涉及动态选择审批人的问题,我们后边会讲到)
global class OppApprovalProcess { //submit
webservice static boolean SubmitforApproval(string oppID, string Comments, string userID)
{
try
{
system.debug('oppID:'+oppID);
User nextapprover = getApprover(oppID);;
Approval.ProcessSubmitRequest subReq = new Approval.ProcessSubmitRequest();
subReq.setComments(Comments);
subReq.setObjectId(oppID);
subReq.setSubmitterId(userID);
subReq.setNextApproverIds(new Id[]{nextapprover.Id});
subReq.setProcessDefinitionNameOrId('Opportunity_Discount');
Approval.ProcessResult submitResult = Approval.process(subReq); return submitResult.isSuccess();
}
catch(Exception ex)
{
system.debug('ex:'+ex.getMessage());
return false;
}
}
}
3,创建完按钮后,我们需要把这个自定义按钮添加到page layout中,我们的最终目的是在添加完成后替换原有默认的提交按钮,所以我们要重写原有的Opportunity的Detail页面通过Jquery进行代码注入,所以我们要新建一个vistualforce 页面代码如下:
<apex:page sidebar="true" standardController="Opportunity">
<!-- <apex:relatedList list="ProcessSteps" ></apex:relatedList>-->
<apex:includescript value="{!$Resource.JQuery}"/>
<script type="text/javascript">
$(function(){ //添加新按钮隐藏老按钮
// alert($('input[name="piSubmit"]').val());
if($('input[name="piSubmit"]').val()=='Submit for Approval')
{
($('input[name="piSubmit"]').hide()).parent().append($('input[name="submit_for_approval"]'));
$('input[name="piSubmit"]').next().hide();
}
else
{
//alert($('input[name="piSubmit"]').val());
$('input[name="submit_for_approval"]').hide();
//替换HistoryList中的审批链接
var OppId = ('{!Opportunity.Id}').substring(0,15);
var ApprovalListID = OppId + '_RelatedProcessHistoryList_body';
//alert(ApprovalListID);
var Approvalprocessdiv=document.getElementById(ApprovalListID);
//alert(Approvalprocessdiv.getAttribute('class'));
if(Approvalprocessdiv!=null)
{
var originalHTML=Approvalprocessdiv.innerHTML;
var newHtml=originalHTML.replace('/p/process/ProcessInstanceWorkitemWizardStageManager?','/apex/ProcessInstance?OppId='+OppId+'&');
Approvalprocessdiv.innerHTML=newHtml;
}
}
});
</script>
<apex:detail relatedList="true" title="true"/>
</apex:page>
添加完成后效果如下:submit for approval by Neo 就是我们的自定义按钮
4,添加提交按钮后,我们同时要替换审批页面的同意和拒绝按钮,但是由于salesforce不支持重写这个页面,所以我们自己创建一个审批页面来替换salesforce默认的审批页面,前端代码如下:
<apex:page controller="ProcessInstanceController" tabStyle="Opportunity">
<apex:form >
<apex:sectionHeader title="Opportunity" subtitle="{!objOpp.Name}"/>
<apex:pageBlock title="Approve/Reject Approval Request">
<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Approve" action="{!Approval}" reRender="block">
<apex:param name="approve" value="Approve" assignTo="{!ApprovalAction}"/>
</apex:commandButton>
<apex:commandButton value="Reject" action="{!Approval}" reRender="block">
<apex:param name="reject" value="Reject" assignTo="{!ApprovalAction}"/>
</apex:commandButton>
<apex:commandButton value="Cancel" action="{!Approval}" reRender="block">
<apex:param name="cancel" value="Cancel" assignTo="{!ApprovalAction}"/>
</apex:commandButton>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="1">
<apex:pageBlockSectionItem >
Name <apex:outputField value="{!objOpp.Name}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
Lead Owner <apex:outputField value="{!objOpp.Owner.Name}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
Rejection Reason <font color="red">(Mandatory while Rejection)</font><apex:inputField value="{!objOpp.Rejection_Reason__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
Comments <font color="red">(Mandatory while Rejection)</font> <apex:inputTextArea value="{!objOpp.Comments__c}" rows="5" cols="100"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
5,同时在后台类中重写Apprve 和 Reject 类,代码如下:
public class ProcessInstanceController {
public String processId;
public String OppId;
public ProcessInstance objProcessInstance;
public Opportunity objOpp {get; set;}
public string ApprovalAction {get;set;}
public PageReference redirectPage;
//初始化
public ProcessInstanceController()
{
processId = ApexPages.currentPage().getParameters().get('id'); //获取当前的工作流ID
OppId = ApexPages.currentPage().getParameters().get('OppId'); //获取当前case ID
objOpp = [select Name,Owner.Name,Rejection_Reason__c,Comments__c from Opportunity where id =:OppId]; //获取当前Opp对象为了后面更新comments和Reson
redirectPage = new PageReference('/'+OppId);
}
//审批
public PageReference Approval(){
try
{
if(ApprovalAction == 'Approve' || ApprovalAction == 'Reject')
{
//system.debug('ApprovalAction:'+this.ApprovalAction);
User nextapprover =[select Id from User where username = 'yinghai_guo_neo@sina.com'];//新建立一个object 并mapping关系
Approval.ProcessWorkitemRequest approvalNode = new Approval.ProcessWorkitemRequest();
// system.debug('comments:'+objOpp.Comments__c);
approvalNode.setComments(objOpp.Comments__c);
approvalNode.setAction(ApprovalAction);
approvalNode.setNextApproverIds(new Id[]{nextapprover.Id});
approvalNode.setWorkitemId(processId);
//system.debug('processID'+processId);
Approval.ProcessResult result = Approval.process(approvalNode);
//system.debug('result:'+result.isSuccess());
update objOpp;
//system.debug('update objOpp');
}
else
{
//system.debug('ApprovalAction:'+this.ApprovalAction);
}
}
catch(Exception ex)
{
system.debug('Ex:'+ex.getMessage());
}
return redirectPage;
}
}
最后生成的审批页面效果如下:
6, 最后我们要做的事情就是在动态查找审批人的方法,我们通过判断审批的每个节点等条件赛选出最终审批人
//get approver
private static User getApprover(string OppID)
{
string ProcessNodeName = 'Sumbit';
//获取当前需要审批节点名称
for (ProcessInstance piw:[select Id,(SELECT ProcessNode.Name FROM StepsAndWorkitems)
FROM ProcessInstance where TargetObjectId = :OppID order by CreatedDate])
{
for(ProcessInstanceHistory PIH : piw.StepsAndWorkitems)
{
ProcessNodeName=PIH.ProcessNode.Name;
break;
}
}
User nextApprover = null;
if(ProcessNodeName == 'Submit')
{
//do sth
}
else if(ProcessNodeName == 'Director Approval')
{
//do sth
}
else if(ProcessNodeName == 'CEO Approval')
{
//do sth
} return nextApprover;
}
7,由于我们的opportunity 的页面是我们自定义的,所以我们要在系统中替换Opportunity list View按钮中的链接子页面,我们直接在Buttons, Links, and Actions修改,截图如下:
至此,我们实现审批人的动态审批,有任何问题,留言讨论,谢谢!!!