0

I have 2 different apex:actionFunction, one is for save, the other is for saveAndNew:

<apex:form >
<apex:actionFunction name="save" action="{!save}" status="sub-status"/>
<apex:actionFunction name="saveandnew" action="{!saveAndNew}" status="sub-status"/>
</apex:form>

currently, I am using 2 controller methods to make them work, 'save' and 'saveAndNew'

public PageReference save(){
//save codes here
PageReference pageRef= new PageReference('/'+returnId);
pageRef.setRedirect(true)}

public PageReference saveAndNew(){
//the same save codes
PageReference pageRef = new PageReference('/apex/page2');
pageRef.setRedirect(true);
return pageRef;}

The problem is, both methods have the same line of codes for 'save' and the only difference is the returned page reference. How can I make this into one method? can I use apex:param? if so, how may I write it? I'm so stuck on this...

1

Posts such as apex:actionFunction with apex:param Param not setting show how to pass parameters in apex:actionFunction calls. While it is possible and sometimes a good idea to do it, the necessary code isn't particularly elegant or clear. So for your case factoring out the common code in Apex (or just leaving a small amount of duplication) is probably the cleaner approach:

public PageReference save() {
    return save('/'+returnId);
}

public PageReference saveAndNew() {
    return save('/apex/page2');
}

private PageReference save(String nextUrl) {
    // save code here
    PageReference pageRef = new PageReference(nextUrl);
    pageRef.setRedirect(true);
    return pageRef;
}
  • Posted at the same time you did @keith :) – RedDevil Jun 26 '18 at 7:47
1

Create a new method with below code and pass the page reference parameter into it

    public PageReference save(string pageref){
    //common save code
    PageReference pageRef = new PageReference(pageref);
    pageRef.setRedirect(true);
    return pageRef;
}

Pass apex param from action function and you can achieve your desired result.

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.