Skip to main content

Salesforce Visualforce Apex - Getter and Setter methods – How to use them

Getter and setter methods are used to pass data from your visualforce page to your controller and vice versa.

Get accessor : The "get" accessor is used to pass data from your Apex code to your Visualforce page. The code in a get accessor executes when the property is read.

public string getuserinput()
{ return userinput; }

Set accessor : The "set" accessor is used to pass values from your visualforce page to the controller. The code in a set accessor executes when the property is assigned a new value.

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

In our example what we see is, the variable "userinput" is declared as string data type. Apex is strongly typed language and when you declare a variable you need to specify its data type.

The value entered in visualforce page via inputfield : userinput , is passed to the Apex code ( setuserinput ) . The value is stored in declared variable - userinput .The value is returned back to Visualforce page via Get accessor getuserinput , hence you are able to see the entered value back on the visualforce page. .

Custom Controller Apex Code :



Visualforce page Code :



The output when previewed on salesforce lightning platform :


Comments