Overload Apex Class to be Controller AND Extension

July 24, 2009 · Filed Under Apex, Development, Visualforce, X-Squared On Demand 

Wow - today brought an interesting discovery. Here's the situation:

Coding the new premium version of Mass Update Contacts (details to come), I replaced the two parts of the page with Apex Components. This will allow the app to support custom address fields and international address formats.

I didn't want to write one ControllerExtension for the main page, a CustomController for the view section component, and another CustomController for the pageblocktable component. So here is the overloaded class constructor. Note that this works because an extension passes the StandardController to the constructor, and a CustomController passes nothing:

public with sharing class VersatileClass {

private Account account;

public VersatileClass(){
	system.debug('OPERATING AS CONTROLLER');
		if(System.currentPageReference().getParameters().get('id')==null){
			//Include error checking here
		} else{
			string AId = System.currentPageReference().getParameters().get('id');
			account = [select id, name from Account where id = :AId];
			//And whatever else you want to do
		}
}

public VersatileClass(ApexPages.StandardController controller) {
	system.debug('OPERATING AS EXTENSION');
		if(System.currentPageReference().getParameters().get('id')==null){
			//Include error checking here
		} else{
			this.account = (Account)controller.getRecord();
			//And whatever else you want to do
		}
	}
}

Enjoy! This should save people a lot of time.

Comments

3 Tweets 1 Other Comment

5 Responses to “Overload Apex Class to be Controller AND Extension”

  1. a_sinclair on July 24th, 2009 14:08

    RT @dschach: Code to overload class as controller and/or extension http://tinyurl.com/n4xj7g #iusesalesforce #sfdc #salesforce

    This comment was originally posted on Twitter

  2. Steve Andersen on July 24th, 2009 14:12

    Very nice Dave! that’s a great way to use the ability to create multiple constructors.

  3. kylemroche on July 24th, 2009 17:05

    RT @dschach: Code to overload class as controller and/or extension http://tinyurl.com/n4xj7g #iusesalesforce #sfdc #salesforce

    This comment was originally posted on Twitter

  4. LeviDayley on July 24th, 2009 17:21

    Great Info! RT @dschach: This one’s for you: Code to overload class as controller and/or extension http://tinyurl.com/n4xj7g #iusesalesforce

    This comment was originally posted on Twitter

  5. Sebastian Wagner on September 14th, 2009 06:55

    Awesome, excatly what I need for my current project :D

Leave a Reply




Additional comments powered by BackType