function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chandrasekhar Reddy 5Chandrasekhar Reddy 5 

Expected output?

I have below controller:
public class MyController {
public string cString { get; set;}

public string getStringMethod1(){
return cString;
}

public string getStringMethod2(){
if(cString == null)
cString = 'Method2';
return cString;
}
}
VF:
<apex:page controller="MyController">
{!cString}, {!StringMethod1}, {!StringMethod2}, {!cString}
</apex:page>
Actual Output:
, , Method2,

But I am expecting output : , , Method2,Method2

Why so? Why is cString value not retained though it is being set in getStringMethod2 method?



 
SalesFORCE_enFORCErSalesFORCE_enFORCEr
You have to reRender page to get the updated value.
Jerun JoseJerun Jose
Hi Chandra,

Have a look at the order of execution for VF pages.
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_get_request.htm

The page expressions are evaluated and the values are returned using the get method

In your case, when the VF engine goes through the page.
1. {!cString} - at this point value is null - so print null.
2. {!StringMethod1} - still value is null - print null
3. {!StringMethod2} - in this getter method, the value of cstring is set to "Method2", so print "Method2".
4. {!cString} - now the value is "Method2" as it was set in step3, so print "Method3".

I can see that you are just experimenting here, but I would recommend to set the values of your variables during the page initialize using a constructor.
 
Chandrasekhar Reddy 5Chandrasekhar Reddy 5
Hi Jerun,

Thanks for your reply. I am not sure what is 'Method3' in your reply. My hunch is that it is a typo error. I thought the same way as you explained.

But the actual output is not
, , Method2,Method2
It prints the output
, , Method2,
Per your explanation, you are also expecting the output as I am
, , Method2,Method2
My question is,  how is getting printed , , Method2, instead of , , Method2,Method2      ?
 
SalesFORCE_enFORCErSalesFORCE_enFORCEr
cString was already set a null when the page was loaded so if you are changing its value then you need to reRender it to fetch the updated value. Try putting the variable inside a outputtext or outputpanel and then reRender it using a button click you will see the updated value 
Basu, SaikatBasu, Saikat

i know its late, but this may help other readers. 

https://salesforce.stackexchange.com/questions/169596/need-help-understanding-get-set-methods-weird-behavior