How to implement Save and New functionality on a VisualForce page

I know this is how to save a record

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

Now I want the button to save the current record and reset the form for entering another record.

Something like that...

 <apex:commandButton action="{!SaveAndNew}" value="Save & New"/> 
+4
source share
2 answers

The URL of the new entry page is {org URL} / {3-letter prefix object} / e? "

You can define your save method as follows, where m_sc is a reference to the standard controller passed to your extension in it:

  public Pagereference doSaveAndNew() { SObject so = m_sc.getRecord(); upsert so; string s = '/' + ('' + so.get('Id')).subString(0, 3) + '/e?'; ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.Info, s)); return new Pagereference(s); } 

To use your controller as an extension, modify its constructor to get the StandardController link as an argument:

 public class TimeSheetExtension { ApexPages.standardController m_sc = null; public TimeSheetExtension(ApexPages.standardController sc) { m_sc = sc; } //etc. 

Then simply change the <apex:page> on your page to refer to it as an extension:

 <apex:page standardController="Timesheet__c" extensions="TimeSheetExtension"> <apex:form > <apex:pageMessages /> {!Timesheet__c.Name} <apex:commandButton action="{!doCancel}" value="Cancel"/> <apex:commandButton action="{!doSaveAndNew}" value="Save & New"/> </apex:form> </apex:page> 

Note that you do not need an extension in the class name, I just made it reasonable. You do not need to change anything else on your page to use this approach.

+3
source

Ideally, you can use the ApexPages.Action class for this. But when I tried to use it, it was too buggy. It has been a while, so you can play with it using the {!URLFOR($Action.Account.New)} .

To work, just use PageReference to redirect the user to the new URL.

For example, if these were for accounts,

 public PageReference SaveAndNew() { // code to do saving goes here PageReference pageRef = new PageReference('/001/e'); return pageRef; } 
+2
source

Source: https://habr.com/ru/post/1391770/


All Articles