Getter and Setter methods in salesforce

Getter and Setter methods in salesforce are used to pass data from controller to visualforce and vice versa.

Let’s take a scenario where user wants to display a text box in visualforce page,

So once he entered some value in text box means through setter method value will be passed from visualforce page to controller ( Apex class) and same can be retrieved back to visualforce page through controller getter method



getter and setter methods in salesforce,salesforce examples, sfdcpanda, sfdc panda, dineshkumar rajamani, salesforce online training, salesforce tutorial


So go ahead and create a simple vf page and apex code

visualforce page:-

<apex:page controller="getsetExample">
 <apex:form >
 <apex:outputlabel value="Enter your name here"/> 
 <apex:inputtext value="{!userinput}">
 <apex:actionsupport event="onchange" rerender="DispId" />
 <apex:outputpanel id="DispId"> 
 <apex:outputtext value="The name entered is {!userinput}"/>

Apex  class :-

public class getsetExample
    public String userinput{get; set;}

In this example what happens is the variable “userinput” stores the value entered in visualforce page by the user and passes it to the Apex code., Hence you are able to see the entered value in the visualforce page through getter method¬†where ‘on change’ action support function associated with text box which makes ajax call.

Once Ajax call completed, rerender which refreshes the outputpanel id called 'DispId' to display the latest value from controller.

To make things simple, lets make a simple change in Apex code to understand getter method.

public class getsetExample
 public String userinput = 'Dk' ;

 public String getuserinput(){return userinput ;}
 public void setuserinput(String userinput)
 this.userinput = userinput;

Whenever the page gets loaded, it always display ‘Dk’ because initial value for the variable userinput i have given is ‘Dk’ but whenever you enter some other value than ‘Dk’ it will bring you the latest value on the parallel output panel in VF page as shown in above image.

Be the first to comment

Leave a Reply

Your email address will not be published.