Wednesday 9 September 2020

Episode-9 Getter and Setter Methods in Salesforce

In this blog, we will learn about using getter and setter methods in the apex controller class. Before wasting any time lets get started😊




Getter Method is used to pass data from the apex controller class to Visualforce Page and Setter Method is used to set the value back to the controller variable. 

Let's understand this concept using an example scenario.

The user wants to display the value entered in the text box after clicking on the Display button on the VF page.

So, In this case, when the user enters the value in the input box the value will be passed from the Visualforce Page to the controller (apex class) through the Setter Method and store in the controller variable. The same value can be retrieved back to the VisualforcePage from the Controller using the Getter Method which is being displayed in the output text as shown in the VF Page below.







Let's understand the scenario better by the code. First, we will create the Visualforce Page for this example and then the controller class for it.

Visualforce Page




Controller Apex Class





Explanation:

In order to use the controller class in the VF Page use the keyword controller="ClassName".


In this example the binding variable  'userinput' stores the value entered by the user in the input text on the VF Page and passes to the controller class variable userinput via Setter Method i.e setuserinput().
Setter methods must always be named as setVariableName.

The same value is returned to the VF Page output text  through the Getter Method i.e getuserinput()
Hence after clicking on Submit Button, the value is displayed on the VF page in the output text.
Getter methods must always be named as getVariableName.




There is also the shortcut code to write the getter and setter methods as shown below:


Isn't it cool your code reduces to one line using the above syntax.

Also, refer to the Visualforce Developer Guide to know about the usage of different tags used in the Visualforce Page. Below is the link for your reference



Thanks for reading my blog. For the next episode of learning stay tuned till then keep learning and sharing your knowledge. Also, do comment if this blog was helpful to you.








.














No comments:

Post a Comment

If you have any doubts ,Please let me know.

Episode 13 : RollUp Summary Trigger for Lookup Relationship

 As we all know we can use roll-up summary field logic only for the master-detail relationship, but in case you have the business requiremen...