Sunday 26 August 2018

Dynamic Picklists in Custom Component Property | VisualEditor.DynamicPickList | Dynamic Picklists in Lightning with Apex



We can create a component property as a picklist to configure the component in the Lightning App Builder. With the help of "VisualEditor.DynamicPickList" we can create a dynamic picklist and can fetch the data from Sobject/Custom Setting as well.

In our previous post we talk about "Design Resource" and created one "favoriteColors" "design:attribute" to create picklist. In that post we provided the hardcoded value in "datasource". Let see how to add Dynamic value in Picklist Property.

Step 1) Create on Apex class and Extend the VisualEditor.DynamicPickList abstract class.

 DynamicPicklistController Apex Class

global class DynamicPicklistController extends VisualEditor.DynamicPickList{
    global override VisualEditor.DataRow getDefaultValue(){
        VisualEditor.DataRow defaultValue = new VisualEditor.DataRow('red', 'RED');
        return defaultValue;
    }
    global override VisualEditor.DynamicPickListRows getValues() {
        VisualEditor.DynamicPickListRows  myValues = new VisualEditor.DynamicPickListRows();
        List<Color__c> listColor = [SELECT Name,ColorCode__c FROM Color__c limit 10 ];
        for(Color__c col: listColor){
            myValues.addRow(new VisualEditor.DataRow(col.ColorCode__c, col.Name));
        }
        return myValues;
    }
}

Step 2) Add an Attribute to your Design File.

DynamicPicklist.design

<design:component>
    <design:attribute name="favoriteColors"  label="Color" datasource="apex://DynamicPicklistController"/>
</design:component>

DynamicPicklist.cmp

<aura:component implements="flexipage:availableForAllPageTypes,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
   <aura:attribute name="favoriteColors" type="String" access="global"/>
   <div >
        <div class="slds-text-heading_large" style="{!'color:' + v.favoriteColors}" >
            Welcome In Lightning
        </div>
   </div>
</aura:component>

Here is result








Thanks,
Amit Chaudhary
Capture.JPG  @amit_sfdc    #SalesforceApexHours    @ApexHours
  Salesforce Apex Hours

1 comment:

  1. Hello Amit. Its really very helpful. I just have one question... if I want to dynamically show the fields of SObjects in design attribute, is there any way to pass the sObjectName from component to class so that I can get the fields list of the object where i have used the component.

    ReplyDelete