Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement "Cancel" functionality in a VisualForce Page

I know that this is how to save a record

<apex:commandButton action="{!save}" value="Save"/>

I want a button to NOT save the current record (ie. Cancel) and navigate to the list of saved record (ie. list of objects for that object type).

Something like this...

<apex:commandButton action="{!cancel}" value="Cancel"/>
like image 620
Sam Avatar asked Jan 19 '12 05:01

Sam


2 Answers

The list view for an object is your base URL / the 3 letter prefix for your object / o, for example:

https://na1.salesforce.com/a0C/o

So you could just create an action method that returns a Pagereference with the appropriate URL and set to redirect (pr.setRedirect(true)).

Alternatively, you could use your controller as an extension to a standard controller, and just call cancel on the standard controller:

// controller extension
public class TimeSheetExtension
{
  ApexPages.standardController m_sc = null;

  public TimeSheetExtension(ApexPages.standardController sc)
  {
    m_sc = sc;
  }

  public PageReference doCancel()
  {
    return m_sc.cancel();
  }
}

// page
<apex:commandButton action="{!doCancel}" value="Cancel"/>

Note that this doesn't necessarily take you to the list view, it'll return you to the last page you were viewing before going to the VF page.

like image 91
Matt Lacey Avatar answered Sep 29 '22 13:09

Matt Lacey


You should also add the immediate tag to your Cancel button, so that the form doesn't run any validation before performing the Cancel operation.

<apex:commandButton action="{!cancel}" immediate="true" value="Cancel"/>

See http://blogs.developerforce.com/developer-relations/2008/12/using-the-immediate-attribute-on-commandlinks-and-commandbuttons.html

like image 29
Piran Avatar answered Sep 29 '22 12:09

Piran