3

I have a VisualForce page testPage

<apex:page controller="testController">
    {!myString}, {!myString1}, {!myString2}, {!Mystring3}, {!myString}
</apex:page>

And the controller is

public class testController {
    public string myString {get;set;}
    public string getMyString1()
    {
        return myString;
    }

    public string getMyString2()
    {
        if(myString==null)
            myString = 'Method2';
        return myString;
    }

    public void getMystring3()
    {
        myString = 'Method3';
    }
}

When loading the page, it outputs , , Method2, ,. The methods getMyString2 and getMystring3 both set the property. Why the myString property is not set here?

Noor A Shuvo
  • 2,639
  • 3
  • 23
  • 48

2 Answers2

0

I know Salesforce used to reserve the word "test" for test classes. If it's not firing at all, try renaming it. Salesforce may thing they're test classes.

0

When evaluating the merge expressions in the page:

{!myString}, {!myString1}, {!myString2}, {!Mystring3}, {!myString}

The order of events is:

1., testController get(myString), which is null, since the variable hasn't been initialized

2., testController get(myString1), which is also null since the value being returned is still null

3., testController get(myString2), which sets the variable myString to the value of Method2 and returns that value

4., testController get(Mystring3), which returns sets the variable myString to the value Method3 and returns nothing

5., That's it. Even though {!myString} is written again in the visualforce page, the page doesn't go back to the controller to get the value again, since it already got it once and already knows it's value; assuming (mistakenly in this case) that the value hadn't changed.


If you changed your VF page to:

<apex:page controller="testController">
    {!myString1}, {!myString2}, {!Mystring3}, {!myString}
</apex:page>

testController get(myString) would be called after testController get(Mystring3), so the resulting page would display:

, Method2, , Method3


All that being said, a getter shouldn't change the state of a program, and if you are relying on this type of behavior, it will only make your code hard to understand.

martin
  • 1,102
  • 2
  • 12
  • 20