Thursday, December 8, 2016

Visualforce - Beyond Basics Series 7 - Controller polymorphism using init action

What is Constructor Polymorphism ?

It's the method of initializing a object differently based on different context. This is achieved though init action in the page tag.


When it is useful ?

In many cases, you need to share the controller, extension between different pages/components. But, it wont be possible if the object is initialized with default set of values. So, you may need to initialize the object very differently for different cases.


Where is the code ?

I have a Class in Apex which will be shared among two pages. These pages will initialize the object differently. This is just a basic case, but, it could initialize or perform certain logic & make the object look entirely different.



public class testcls7_08122016 {
public string pagemessage { get; set;}
public testcls7_08122016() {
pagemessage = 'page initialized to default value';
}
public void init_page1() {
pagemessage = 'page initialized by page1';
}
public void init_page2() {
pagemessage = 'page initialized by page2';
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
<apex:page controller="testcls7_08122016" action="{!init_page1}">
<apex:outputText value="{!pagemessage}"/>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub
<apex:page controller="testcls7_08122016" action="{!init_page2}">
<apex:outputText value="{!pagemessage}"/>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub

No comments:

Post a Comment

Thanks for reading my blog !