Before creating a custom button or link, determine what action you want to occur when a user clicks it. Consider a Visualforce page if you want the button or link to launch a custom page or other code(salesforce help).
We can execute Javascript or Apex Class within a visualforce page action.But we will not talk about the Onclick today,you can achieve your business by webservice or remote object.
Today we will implement a custom button through a visualforce page, in the page ,init a Action and accomplish the logic in the apex controller
The scenario is described below:
1,When our business unit launched a campaign,the user will apply marketing budget.Certainly,we will manage the approve flow by salesforce standard approve process.
2,We Create a custom object: event request,and it has a field named status and contains these picklist value (Submitted, Approved, Reject, Cancelled );
3,The status field is read only to the user,and update by approve process
4,But there is a question,when the user want to cancel the request,he can not change the status field directly
5,So,we need a Cancel Button to do it.
Here is the flows:
1,Create a visualforce page,very simple :
<apex:page standardController="Event_Request__c" extensions="ctrlExt_EventRequestCancel" action="{!customCancel}"> <apex:Pagemessages id="msgs"/> <apex:sectionHeader title="Auto-Running Apex Code"/> <apex:outputPanel > If you see this page, it must be something wrong.Please contact the administraor. </apex:outputPanel> </apex:page>
2,Create a extension controller
public with sharing class ctrlExt_EventRequestCancel { private final ApexPages.StandardController stdController; public Event_Request__c eq{get;set;} public ctrlExt_EventRequestCancel(ApexPages.StandardController stdController) { this.stdController = stdController; list fieldsList = new list (); fieldsList.add('Status__c'); if(!Test.isRunningTest()) { stdcontroller.addFields(fieldsList); } this.eq = (Event_Request__c)stdcontroller.getRecord(); system.debug('this.eq1: ' + this.eq ); } public PageReference customCancel() { try { if(null != this.eq && 'Cancelled' != this.eq.Status__c) { this.eq.Status_MDT_AP__c='Cancelled'; update this.eq; return this.stdController.view().setRedirect(true); } }catch(exception e) { ApexPages.Message Msg = new ApexPages.Message(ApexPages.Severity.Info,e.getMessage()); ApexPages.addMessage(Msg); } return null; } }
3,In the Object describe page,create a new button:
4,Congratulations,you have got a new Custom Button.