[SalesForce] Void Method inside of Pagereference method does not fire

I have two different code samples. I am calling the PageReference method as an action on a CommandButton.

Code Sample 1:

public without sharing class MyClass{
    public MyClass{

    }
    public void createRecord1(){
        account a = new account(name = 'Test');
        insert a;
    }
    public void createRecord2(){
        account b = new account(name = 'Test2');
        insert b;
    }
    public PageReference createRecords(){
        system.debug('inside pagereference');
        createRecord1();
        createRecord2();
       system.debug('about to exit pagereference');
       return null;
    } 
}

Code Sample two:

public without sharing class MyClass{
    public MyClass{

    }

    public PageReference createRecords(){
        system.debug('inside pagereference');
        account a = new account(name = 'Test');
        insert a;
        account b = new account(name = 'Test2');
        insert b;
        system.debug('about to exit pagereference');
        return null;
    }
} 

When I use Sample 1, the createRecords method fires, but the records don't get created even though when I look at the debug logs I can clearly see the entry and exit points for the methods called within it. However, when I use Sample two and call the createRecords method from the commandbutton I get the expected result which is that the records are created. Is there any particular reason for this behavior? Thanks for any suggestions or pointers.

Best Answer

This class and VF page works just fine in my tests.

So there is something you are doing between iterations that is different or something on your page that is weird causing it. I would suggest to comment out everything and try it to see if it works, then uncomment sections at a time and test and see when it breaks then narrow it down from there.

Class:

public without sharing class MyClass{
    public MyClass(){

    }
    public void createRecord1(){
        account a = new account(name = 'Test');
        insert a;
    }
    public void createRecord2(){
        account b = new account(name = 'Test2');
        insert b;
    }
    public PageReference createRecords(){
        system.debug('inside pagereference');
        createRecord1();
        createRecord2();
       system.debug('about to exit pagereference');
       return null;
    } 

    public PageReference createRecords_two(){
        system.debug('inside pagereference two');
        account a = new account(name = 'Test');
        insert a;
        account b = new account(name = 'Test2');
        insert b;
        system.debug('about to exit pagereference');
        return null;
    }    
}

VF Page:

<apex:page controller="MyClass">

<apex:form >

<apex:commandButton action="{!createRecords}" value="ONE" rerender="msgs"/>
<apex:commandButton action="{!createRecords_two}" value="TWO" rerender="msgs"/>

</apex:form>


</apex:page>
Related Topic