How to implement “Save & New” functionality in a VisualForce Page

我与影子孤独终老i 提交于 2019-12-30 10:14:06

问题


I know that this is how to save a record

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

Now I want a button to save the current record and reset the form to input another record.

Something like this...

<apex:commandButton action="{!SaveAndNew}" value="Save & New"/>

回答1:


The URL for the new record page is the {org URL}/{3 letter object prefix}/e?".

You could define your save method as follows, where m_sc is a reference to the standardController passed to your extension in it's constructor:

  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 it's constructor to take a StandardController reference as an argument:

public class TimeSheetExtension
{
  ApexPages.standardController m_sc = null;

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

  //etc.

Then just modify your <apex:page> tag in your page to reference 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 don't need Extension in the class name, I just did that to be sensible. You shouldn't need to modify anything else on your page to utilise this approach.




回答2:


Ideally, you could use the ApexPages.Action class for this. But when I've tried to use it, it's been too buggy. It's been a while, so you might want to play with it using the {!URLFOR($Action.Account.New)} action.

What will work is simply using a PageReference to redirect the user to the "new" URL.

For example, if this were for Accounts,

public PageReference SaveAndNew() {
    // code to do saving goes here

    PageReference pageRef = new PageReference('/001/e');
    return pageRef;
}


来源:https://stackoverflow.com/questions/8921414/how-to-implement-save-new-functionality-in-a-visualforce-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!