1

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?

0

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);
    }
}
2
  • This is awesome! Thank you! Worked exactly as needed. Does this have a lot of overhead on the page? How about unit test coverage? As long as I have unit tests for the extensions, the Registry class should get covered? – Dman100 Jun 7 '18 at 18:11
  • @Dman100 Don't know of any particular overhead and yes the registry class will get covered as a side effect. – Keith C Jun 7 '18 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.