Skip to main content
I want to use 2 constructors within my Controller class, one for a VF component and another for VF page.is it possible to have the same SOQL within 2 constructors.Please give an example
3 answers
  1. Mar 13, 2018, 7:49 AM
    Hello

    kindly consider this example 

    Class: 

     

    public with sharing class C {

    public C() {

    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Zero-constructor called'));

    }

    public C(C controller) {

    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Single-argument C called'));

    }

    }

    If your page written like this:

    <apex:page controller="wrapperAccountOpportunity" ...

    Then the zero-parameter constructor will be called.

    If your page is written like this:

    <apex:page standardController="Account" extensions="wrapperAccountOpportunity" ...

    Then the constructor with the single parameter ApexPages.StandardController will be called.

    If you want to call fetchQuery  from both constructors, you'll have to call it from both constructors. Only one constructor will ever be called per controller or extension.

    And, given the following page:

     

    <apex:page controller="C" extensions="C">

    <apex:messages />

    </apex:page>

    You may expect both constructors to be called, but instead, you'll find only the zero-length (default) constructor is called, since the class is referenced twice. In this sense, classes that become controllers are actually singletons in Visualforce. The controller version of the class is only instantiated once; it can still be constructed normally multiple times within the code itself, but Visualforce will only instantiate one automatically.

    Hope its clear.

     
0/9000