[SalesForce] How to populate design attribute datasource automatically

We are using lightning components in a lightning community. When a user drag-drops a component in the community builder, in the configuration options we give user ability to select image names and based on that selection, populate the background of lightning component dynamically.

We are storing images in a static resource that is publicly cached. In design files of components, we have hard-coded image names of the images that are being uploaded in static resource. Then, we dynamically construct the path to that image based on user selection and standard static resource path like:

var imagepath = $A.get('$Resource.Images') + '/assets/images/' + component.get('v.userSelectedImageName');

Design file:

<design:attribute name="bannerImage"
                      datasource = "header.jpg, background.jpg, footer.jpg, Wooden.jpg,contentImage1.jpg"
                      label="Banner Image." />

The problem here is that whenever user wants to add a new image, he has to update static resource and subsequently access the code and edit design file and add the name in datasource of design attribute. This may not be always possible as end user may not have access to code.

In this case, is there any way we can populate the datasource of design attribute dynamically? For ex, fetching the values from a custom setting on init of component etc?

Best Answer

You can generate the list dynamically from Apex. The basic framework looks like this:

global class MyCustomPickList extends VisualEditor.DynamicPickList{

    global override VisualEditor.DataRow getDefaultValue(){
        VisualEditor.DataRow defaultValue = new VisualEditor.DataRow('red', 'RED');
        return defaultValue;
    }
    global override VisualEditor.DynamicPickListRows getValues() {
        VisualEditor.DataRow value1 = new VisualEditor.DataRow('red', 'RED');
        VisualEditor.DataRow value2 = new VisualEditor.DataRow('yellow', 'YELLOW');
        VisualEditor.DynamicPickListRows  myValues = new VisualEditor.DynamicPickListRows();
        myValues.addRow(value1);
        myValues.addRow(value2);
        return myValues;
    }
}

This was taken directly from the documentation, you'll just need to figure out where you want to draw the data from, which might be custom settings, custom metadata, or something else.