function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SFDC RocksSFDC Rocks 

apex:commandButton: "Save & New" action - how do I do this?

For a custom object, is there a built-in action I can specify within a command button to get a "Save & New" button?
 
<apex:commandButton value="Save" action="{!Save}"/>
 
jeffdonthemicjeffdonthemic
You'll have to create your own code. Something like this should do the trick:

Code:
    public PageReference saveNew() {
        
        try { 
         insert contact; 
        } catch(System.DMLException e) {
            ApexPages.addMessages(e);
            return null;
        }   

        return (new ApexPages.StandardController(new Contact())).edit();        

    }   

 
Jeff Douglas
Informa Plc
http://blog.jeffdouglas.com


VarunCVarunC
One more approach :) ...

Code:
    ApexPages.StandardController con;
    public YourClassName(ApexPages.StandardController controller) {
        con = controller;              
    }

    public PageReference savenew(){
        con.save();

        return (new ApexPages.StandardController(new Contact())).edit();
     }

 



Message Edited by vchaddha on 01-19-2009 07:47 AM
sofogabesofogabe

I tried your code vchaddha, but got a "You cannot call edit() on a null object" error. I'm assuming I missed a step - any thoughts?

 

Thanks!

VarunCVarunC
Sorry .. but I made that code up manually and haven't tried it ... I thought it should work ...
Apple88Apple88

I also got the same error "You cannot call Edit() on a null object" when try to rebuild the Save & New action using controller extension.  Could anyone provide some hints to resolve this?

 

Thanks and best regards

Apple88

reactreact

private ApexPages.StandardController con; public MyController(ApexPages.StandardController stdController) { con = stdController; } public PageReference saveNew() { con.save(); Schema.DescribeSObjectResult describeResult = con.getRecord().getSObjectType().getDescribe(); PageReference pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e'); pr.setRedirect(true); return pr; }

 

Probably too late for the original poster. This is how I solved this problem.

VarunCVarunC
gud approach. Thanks for letting us know :) ...
jkucerajkucera

Thanks for posting React!  Redirrect worked.  

 

However, it doesn't "stop" if errors occurred on the  save & always goes to the new screen.  Any ideas how to catch trigger & validation rule exceptions upon save & prevent the redirrect?

 

I haven't found a solution yet. 

VarunCVarunC

try { con.save(); } catch (Exception ex) { ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, ex.getMessage())); return null; }

This code will show Error message of Trigger or Validation rule on VF page of yours.

jkucerajkucera

Worked like a charm - thanks!

 

 

public PageReference saveNew() { PageReference pr; try{ con.save(); Schema.DescribeSObjectResult describeResult = con.getRecord().getSObjectType().getDescribe(); pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e'); pr.setRedirect(true); return pr; }catch(Exception e){ ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage())); return null; }//try }//saveNew

 

 

 

Apple88Apple88

Hi,

 

I followed the proposed coding for the save & new function and it worked fine and displayed the errors properly that were found by the "before" trigger.  However, it failed to display the errors that were found by the "after" trigger.

 

Any suggestion to resolve this problem?

 

Thanks and best regards

Apple88

goabhigogoabhigo

Hey React,can you tell me what these two lines do actually.

 

Schema.DescribeSObjectResult describeResult = con.getRecord().getSObjectType().getDescribe();

PageReference pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e');

 

 

Thanks.

goabhigogoabhigo

Hey John I followed the same. Clicking on 'Save & New' button works fine. But now if I click on cancel button it displays Home tab. I have written action="{!cancel}" for the Cancel button.

 

Any idea why it happens so?? Any suggestion will be helpful.

 

Thanks.

SScholtzSScholtz

@Apple88... try using

 

ApexPages.addMessages(e);

 

instead of ApexPages.addMessage() (plural method instead of the singular method).

 

Add Message will only spit out one error messages, while Add Messages will spit out all the errors in the exception.

 

@Abhi_the1...not sure why that might be happening, but check to make sure there's a "retUrL" value in the query string of the page you're on when you start.  If there's no retUrl value, it will punt you to the homepage by default. (I think)

 

Some additions to this code that might help anybody else who stumbles on here would be to make sure your Save & New action is passing along any pre-filled values on to the next Create page.  This is important when createing detail objects, so that the Master field is already filled in.

 

My code kinda looks like this...

    /*** PROPERTIES ***/
    private ApexPages.StandardController myStdController;
    public String queryString {get;set;}
    
    /*** CONSTRUCTOR ***/
    public vf_Child_Object_Create(ApexPages.StandardController stdController) {
        myStdController = stdController;
        PageReference thisPage = ApexPages.currentPage();
        List<String> url = thisPage.getUrl().split('\\?');
        queryString = url[1];
    }

    /*** ACTIONS ***/
    public PageReference saveandnew(){
        try {
            myStdController.save();
            
            Schema.DescribeSObjectResult describeResult = myStdController.getRecord().getSObjectType().getDescribe();
            
            PageReference pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e?' + queryString);
            pr.setRedirect(true);
            return pr;  

        } catch(System.DMLException e) {
            // Note: not spitting out any error messages, as SF seems to be handling the errors fine, at least for my simple object; your mileage my vary.
            return null;
        }
    }

 

The querystring that I read during the contructor phase should remain untouched by your processes.  SF will dump in other variables into the querystring, keeping track of the view state, etc. which you don't want.

 

I might be missing something else here, but so far this works for my use cases.

 

Good luck!

EnthEnth

Awesome. I can use that controller to extend any object, massive time saver, thank you!

TommyVTommyV

I have implemented this code in a page that I have created and it is working pretty good.  I am having one issue though.  I'm using this on a custom Task page and it works when creating a new task.  However it does not seem to work on an edit.  My question I guess is, could the pageReference that is being created have the wrong strings being passed to it?  The url seems to be quite a bit different on an Edit.  I apprecitate any direction I can get here.  Thank you!

barniebarnie

thanks for posting Shagz. .  It was really Helpful.

cloud explorer.ax1858cloud explorer.ax1858
This is absolute awesome man..............
FrankJSalinasFrankJSalinas
Shagz,
I used your code and the Save and New worked great until I was finished with Save and New and wanted to just use the default Save button. When I hit the standard Save button, it errored with a "Missing Required Field" message.
I had to add the following code to deal with an Out of Bounds condition on the LIST<String> url.
        List<String> url = thisPage.getUrl().split('\\?');
        if(url.size() > 0) {
         queryString = url[url.size() - 1];
        } else {
         queryString = url[0];
        }
Does anyone know why this was happening and why i had to add a check on the url.size()?
Thanks,
Frank

 
Jason Orbison 6Jason Orbison 6
Just an update if a person wants to do this without any javascript or apex here is how. 

First on the command button, remove the save action and then add onclick event as seen below.

<apex:commmand button action="Save"   ....onclick="savenew();: .... />

then add action function component. 

<apex:actionfunction name="savenew" action="QuickSave" oncomplete="window.location = '{!$CurrentPage.Url}'" />

Actually, if you want to be super cool, you can make this a component and then reuse on all VF pages with just a <c:savenew/> if you put the command button and the action in the component and remove it on the page. 

If anyone cares on how to use this even more powerfully, the reason this works is that salesforce creates the javascript code so you do not have to. the current page url, will work regardless of what instance you are using because it pulls the url of the user and is dynamic so it can be reused on multiple pages. This will not work if you put on an includescript tag as merge fields do not work on those instances. 

Hope you enjoy this quick and clean way of using salesforce to do the heavy lifting and avoid test classes, apex, and javascript, which has to be tested in several browsers.
Mayank Singh DelhiMayank Singh Delhi
Hi All, Can someone let me know how to get "Save & New" button for Custom Objects.??