[SalesForce] Create save button on custom visualforce page to redirect to parent record detail

Hi I'm having an issue with trying to create a save button on a custom VF page that saves the child record that's being created by the user and then redirects back to the parent record detail, which is where the VF page is linked from. I've tried so far to modify the extension with a method to call that would perform the desired function, but that hasn't worked. Here's my extension:

public with sharing class CreateAdditionalPayeeExtension {
    Payee__c payee {get;set;}
    private ApexPages.StandardController stdController;

    //constructor
    public CreateAdditionalPayeeExtension(ApexPages.StandardController stdController){
        this.stdController = stdController;
        payee = (Payee__c)stdController.getRecord();
        payee.Order__c = ApexPages.currentPage().getParameters().get('ordId');
    }

    public PageReference saveAndReturn()
    {
        PageReference cancel = stdController.cancel();
        stdController.save();
        return cancel;
    }
}

Please ignore the second and third lines in the constructor because those are used to autofill a lookup field on the page (works correctly). So in my VF inline editor, I've declared the extension, and the button's line is this:

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

When I click the save button to test it out, it saves the child record successfully but just redirects to the home page. I've tried all sorts of solutions that I've seen online, but none of them have worked properly or have been too complicated for me to modify into a working solution. Any help is greatly appreciated! Thanks in advance!

Best Answer

This is because you are returning the cancel() page reference. The cancel method returns a PageReference of the cancel page. See info here:

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/apex_ApexPages_StandardController_methods.htm

Try simply returning the PageReference object returned by the save() method:

public PageReference saveAndReturn()
{
    return stdController.save();
}

EDIT: I may have misread your post. Returning save() will take you to the detail record of the record you just saved. If you want to navigate back to the parent, you can use the id of the parent like this:

public PageReference saveAndReturn()
{
    stdController.save();
    PageReference parentPage = new PageReference('/' + parent.Id);
    parentPage.setRedirect(true);
    return parentPage;
}