Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have a very simple code to add a record to a custom object. The code is adding the record perfectly fine. However, when I click the command button, it adds the record but also redirects my screen to the added record. I have put the setRedirect(false) condition. I am puzzled here. Please help!

    public PageReference save2() { 
    Sales_Rep_Goal__c cd = new Sales_Rep_Goal__c();
    cd.Sales_Rep1__c = cds.Sales_Rep1__c;
    cd.Year__c = cds.Year__c;
    cd.Month__c = cds.Month__c;
    cd.Rental_Goal__c = cds.Rental_Goal__c;
    insert cd;
    Pagereference pg = new Pagereference('/' + cd.id);
    pg.setRedirect(false);
    return pg;
}
share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

setRedirect will still change the page you are navigating to even if it is false, it just won't change the view state. In your case since you are navigating to a standard page, to a user it basically has the same implementation as a redirection.

This type of redirect performs an HTTP GET request, and flushes the view state, which uses POST. If set to false, the redirect is a server-side forward that preserves the view state if and only if the target page uses the same controller and contains the proper subset of extensions used by the source page.

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_System_PageReference_setRedirect.htm

If you don't want to redirect at all, just return null to stay on the page.

share|improve this answer
    
Thanks Michael. return null worked fine. a little additional help. So through this code, I have created an Add button. I also want to keep delete button on the page, which would delete the record based on values in input fields.. Can you tell me how can I go about it –  Robin Feb 23 at 17:13
    
You may want to post that as a separate question as it is different from the original question. That will ensure other people searching for the same question in the future are able to find it :) –  Michael Welburn Feb 23 at 17:41
    
done. I have posted the question here. If you have time it will be great if you can help me with that. :) salesforce.stackexchange.com/questions/28586/… –  Robin Feb 23 at 18:01
add comment

It still change page when you return PageReference. It pretty standard behavior. Solution for you is just returning null value - this is usual answer for your question.

But If I may, won't be better to simply change this method to void?

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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