【问题标题】:How to implement "Save & New" functionality in a VisualForce Page如何在 VisualForce 页面中实现“保存和新建”功能
【发布时间】:2012-02-13 20:06:59
【问题描述】:

我知道这是保存记录的方法

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

现在我想要一个按钮来保存当前记录并重置表单以输入另一条记录。

这样的……

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

【问题讨论】:

    标签: salesforce apex-code visualforce force.com


    【解决方案1】:

    新记录页面的 URL 是 {org URL}/{3 个字母对象前缀}/e?"。

    您可以按如下方式定义您的保存方法,其中 m_sc 是对在其构造函数中传递给您的扩展的标准控制器的引用:

      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);
      }
    

    要将控制器用作扩展,请修改它的构造函数以将 StandardController 引用作为参数:

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

    然后只需修改您页面中的&lt;apex:page&gt; 标记以将其作为扩展名引用:

    <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>
    

    请注意,您不需要在类名中使用 Extension,我这样做是为了明智。您无需修改​​页面上的任何其他内容即可使用此方法。

    【讨论】:

      【解决方案2】:

      理想情况下,您可以为此使用 ApexPages.Action 类。但是当我尝试使用它时,它太麻烦了。已经有一段时间了,所以您可能想使用 {!URLFOR($Action.Account.New)} 操作来玩它。

      工作的只是使用PageReference 将用户重定向到“新”URL。

      例如,如果这是针对帐户的,

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

      【讨论】:

      • 如果您要在您的开发人员组织之外进行部署,任何带有自定义控制器的解决方案都需要企业版或更高版本。
      猜你喜欢
      • 2021-12-15
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 2019-09-19
      • 2011-04-25
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      相关资源
      最近更新 更多