You need to sign in to do that
Don't have an account?
Abhilash Daslal
Dynamic SOQL used inside a constructor
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
kindly consider this example
Class:
If your page written like this:
Then the zero-parameter constructor will be called.
If your page is written like this:
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:
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.
All Answers
kindly consider this example
Class:
If your page written like this:
Then the zero-parameter constructor will be called.
If your page is written like this:
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:
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.
public without sharing class ClsAccountController{
public List<Account> Accountlist{get; set;}
public Account acc{get;set;}
public Id accId{get;set;}
public ClsAccountController(){
accId = ApexPages.currentPage().getParameters().get('id');
Accountlist= [Select id,Name,Phone,Email where
Account =: accId];
}
public ClsAccountController(ApexPages.StandardController controller){
acc = (Account)controller.getRecord();
Accountlist= [Select id,Name,Phone,Email where
Account =: acc.Id];
}
}
yes use your Dynamic SOQL for both constructor. it wont throw any exception.