Referencing one controller extension from another controller extension

A controller extension can add functionality to a standard controller. The controller extension coding pattern means an extension gets a reference to the standard controller and so can uses its methods:

public with sharing class Ext1 {
    public Ext1(ApexPages.StandardController sc) {
        ...
    }
}

But what if you have a page with two extensions:

<apex:page standardController="Contact" extensions="Ext1, Ext2">
    ...
</apex:page>

and you want to reference the methods of one extension from the other extension? No platform API is provided for that.

Here is some code that allows such cross-referencing. When the extensions are constructed, they are added (registered) into a singleton (static) instance. But a reference to that singleton is also made a field in each extension ensuring that the extension references are made part of the view state. So the cross-references are preserved across form posts etc.

The extensions look like this:

public with sharing class Ext1 {
    private Registry r;
    public Ext1(ApexPages.StandardController sc) {
        r = Registry.instance();
        r.add(Ext1.class, this);
        ...
    }
    private Ext2 getExt2() {
        return (Ext2) r.get(Ext2.class);
    }
}
public with sharing class Ext2 {
    private Registry r;
    public Ext2(ApexPages.StandardController sc) {
        r = Registry.instance();
        r.add(Ext2.class, this);
        ...
    }
    private Ext1 getExt1() {
        return (Ext1) r.get(Ext1.class);
    }
}

and the singleton is:

public class Registry {
    private static Registry instance;
    private Map<Type, Object> m = new Map<Type, Object>();
    // Set a view state field to this
    public static Registry instance() {
        if (instance == null) instance = new Registry();
        return instance;
    }
    // Singleton
    private Registry() {
    }
    public void add(Type key, Object value) {
        m.put(key, value);
    }
    public Object get(Type key) {
        return m.get(key);
    }
}
Advertisements

One thought on “Referencing one controller extension from another controller extension

  1. Pingback: Referencing one controller extension from another controller extension | SutoCom Solutions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s