[SalesForce] Pass controller variable value to another controller class

I have a VF page with two controller extensions…i.e. extensions="Ext1,Ext2"

In my Ext2 class I have some search functionality implemented that allows the user to select records that can be added to another list of records that are already stored in Salesforce that are displayed on the page.

I'm storing the records searched into a static list public static List<Product2> productsToAdd; that is contained in the Ext2 controller class.

Is it possible to pass that value to the Ext1 controller class?

I was trying to access it in the Ext1 class from a method calling the static variable, but it comes back null.

public void addSelectedProducts() {
    system.debug('******************************* Ext2.productsToAdd ' + Ext2.productsToAdd);
    system.debug('******************************* Ext2.testStaticString ' + Ext2.testStaticString);
}

I thought by having both controllers chained in the extensions attribute that I might be able to pass values from one controller to another. Is there a way to accomplish that?

Best Answer

One solution is listed in this blog post of mine Referencing one controller extension from another controller extension.

The technique is to use a registry class that is held in the view state:

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);
    }
}

that the controller extensions can lookup each other through:

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);
    }
}
Related Topic