I have two method both are same only difference is that on the click of save button page should redirects to record detail page after saving data while save & new saves the data but it stays on the same page. Can I do it in simply way I mean I shouldn't write the same method twice.

  • Why not calling the Save method from the Save & New method and then redirect to a page reference? Jan 30, 2017 at 8:03
  • @MartinLezer exactly but I am not getting what condition should I give in if else
    – Anzar
    Jan 30, 2017 at 8:05
  • Oh ok. I didn't understand you wanted to call the same method. If you want to send a param to your save method you can use the apex:param element. Jan 30, 2017 at 8:07

2 Answers 2


Usually I use create 2 methods which calls one common method containing save logic. Both function passes respective URLs.

Following is some psuedo code:

public Pagereference save() {
    return mainSave(null);

public Pagereference SaveAndNew() {
    return mainSave(Page.SamePageAPIName);

public Pagereference mainSave(PageReference pr) {
    try {
        // perform your logic
        // insert some record
        insert objAccount;

        // based on parameter navigate to appropeiate URL
        if(pr == null) {
            return new PageReference('/' + objAccount.Id);
        } else {
            return pr; 
    } catch(Exception objEx) {
        // exception handling
        return null;

You can use same method. There is no need to write two methods. Use upsert statement to save the record. If record already exists, then it will update it else it will create a new record.

And to decide if page should get redirected or not, take a boolean vairable and before upsert statement check if that object contains a 'id'. Any object will have 'id' if it's already there in system. And accordingly check the boolean. After upsert statement add check boolean value and decide if it should get redirected or not. You can refer below sample code.

    Public PageReference Method() {
           Boolean ifalreadyexist = false;

        if(obj.id != null)
           ifalreadyexist = true;
           upsert obj;
        } catch(Exception e){
        if(ifalreadyexist) {
           PageReference pageRef = new PageReference("apex/you_page");
           return pageRef;
        return null;

Hope I answered your question..!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.