function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jyoti Gupta 8Jyoti Gupta 8 

How can I add dynamic option in dataSource of Design Component in lightning component?

I have created an custom component and I am integrate it with Lightning app builder but not able to add dynamic picklist values on app builder page for that component.
RishavRishav
Hii jyoti ,
to generate the option dynamically you can do something like this:
 
<aura:component> <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> <ui:inputSelect label="Select me:" class="dynamic" aura:id="InputSelectDynamic"/>
​ </aura:component>


javascript Controller side code


({
    doInit : function(cmp) {
        var opts = [
            { class: "optionClass", label: "Option1", value: "opt1", selected: "true" },
            { class: "optionClass", label: "Option2", value: "opt2" },
            { class: "optionClass", label: "Option3", value: "opt3" }
           
        ];
        cmp.find("InputSelectDynamic").set("v.options", opts);
    }
})

Hope it will help you. 


Thanks 
Rishav
Jyoti Gupta 8Jyoti Gupta 8
Thanks Rishav for your reply..

But I want to add dynamic picklist in Lightning App Builder Custom Component Properties.
Rodney FarachRodney Farach
I have the same problem and the documentation is very poor. Please, any help will be appreciated!
Tatiana CarpiucTatiana Carpiuc

Hi,
I creaded a dynamic picklist in design resources and it works for me. This is my code:
- design file:
<design:component>
   <design:attribute name="sObjectName" label="Object Name" datasource="apex://DesignResourcePickList" description="" />   
</design:component>
- apex class:
global class DesignResourcePickList extends VisualEditor.DynamicPickList {
   global override VisualEditor.DataRow getDefaultValue(){
       VisualEditor.DataRow defaultValue = new VisualEditor.DataRow('Tree', 'Tree__c');
       return defaultValue;
   }
   global override VisualEditor.DynamicPickListRows getValues() {
       List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();        
       VisualEditor.DynamicPickListRows  myValues = new VisualEditor.DynamicPickListRows();
       for(Schema.SObjectType objectInstance : gd){
           myValues.addRow(new VisualEditor.DataRow(objectInstance.getDescribe().getLabel(), objectInstance.getDescribe().getName()));
       }
       return myValues;
   }
}
The documentation I used is: https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_config_for_app_builder_dynamic_picklists.htm
Miren Echave 5Miren Echave 5
@Tatiana can you share your aura:component code to define the picklist, please?

I am using the following code but not showing the values from the apex class defined in the design:component                             
<ui:inputSelect >
        <aura:iteration items="{!v.picklistValues}" var="pval">
               <ui:inputSelectOption text="{!pval}" label="{!pval}"/>                                   
         </aura:iteration>
</ui:inputSelect>
Thanks
Tatiana CarpiucTatiana Carpiuc
Attribute objName is working right, the others I was trying to get fields of the selected object, but I didn't find a solution...maybe you can do it and share with us ;)

MapViewer.cmp file:
 

<aura:component implements="forceCommunity:availableForAllPageTypes,force:appHostable" access='global'>      
    <aura:attribute name="objName" type="String" default='Tree__c'/>
    <aura:attribute name="sObjectFields" type="String"/>
    <aura:attribute name="sObjectFields1" type="String"/>
    <aura:attribute name="isCustom" type="Boolean"/>
    <aura:attribute name="isStandard" type="Boolean"/>
    
    <c:Map sObjectName='{!v.objName}'/>
    
</aura:component>

MapViewer.design file:

<design:component label="MapViewer">
    <design:attribute name="isStandard" label="Standard Objects"/>
    <design:attribute name="isCustom" label="Custom Objects"/>
    <design:attribute name="objName" label="Object Name" datasource="apex://DesignResourcePickList" description="" />
    <design:attribute name="sObjectFields" label="Object Field" datasource="apex://DesignResourceObjFields" description="" />
    <design:attribute name="sObjectFields1" label="Object Field" datasource="js://test" description="" />
</design:component>

Map.cmp

<aura:component controller='MapCtrl'>
    <aura:attribute name="sObjectName" type="String" access='public'/>       
    <ltng:require styles="/resource/leaflet/leaflet.css" />    
    <ltng:require scripts="/resource/leaflet/leaflet.js" afterScriptsLoaded="{!c.jsLoaded}" /> 


    <div class="map" id="map"></div>
</aura:component>

MapController.js

({
    
    jsLoaded: function(component, event, helper) {
        var action  = component.get('c.getItems');        
        action.setParams({'ObjectType': component.get("v.sObjectName")});
        
        action.setCallback(this, function(response){
            var status = response.getState();
            if(component.isValid() && status === 'SUCCESS'){                
                var data = JSON.parse(response.getReturnValue());
                console.log('data', data)
                setTimeout(function(){
                    var map =  L.map('map', {zoomController:false});
                    L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',{ attribution: 'Tiles © Esri'}).addTo(map);
                    for(var i = 0; i < data.length; i++){  
                        var treeLocation = [data[i].Location__c.latitude, data[i].Location__c.longitude];                        
                        
                        new L.marker(treeLocation)
                            .addTo(map)
                            .bindPopup(helper.generateMarkerPopupContent(data[i]));                         
                    }
                    helper.centerMap(data, map);
                });
            }
        });
        $A.enqueueAction(action);
    }
})

MapHelper.js

({
    centerMap : function(data, map) {
        var treesCoords = [];
        
        for(var i = 0;i < data.length;i++){
            treesCoords.push([data[i].Location__c.latitude, data[i].Location__c.longitude]);
        }
        console.log('treesCoords', treesCoords);
        // create a bounds that will encapsulate every point that is contained in the array
        var bounds = new L.LatLngBounds(treesCoords);
        //This will zoom the map in as far as it can go, while still containing every point in your array
        map.fitBounds(bounds);
    },
    
    generateMarkerPopupContent : function(record) {
        var fields = JSON.stringify(record).split(',');
        console.log('fields', fields);
        var tableBody = '';
        for(var i=0;i<fields.length;i++){
            var name = (fields[i].split(':')[0]).replace(/^"(.*)"$/, '$1');
            var fieldName = name.split('__')[0];
            tableBody += '<tr>' + 
                        '<td class="label">' + fieldName + '</td>' +
                        '<td class="value">' + (fields[i].split(':')[1]).replace(/^"(.*)"$/, '$1') + '</td>' +
                        '</tr>';
        }
         
        var html = '<table>'+ tableBody + '</table>';
        return html;
    }

Map.css

.THIS.map {
    position: relative;
    width:100%;
    height:300px;
}

MapCtrl.apex

public with sharing class MapCtrl {
    @AuraEnabled
    public static String getItems(String ObjectType) {
        
        System.debug('ObjectType:::' + ObjectType);
        String soql = 'SELECT ' + getAllFields(ObjectType) + ' FROM ' + ObjectType;
        System.debug('soql:::' + soql);
        List<SObject> objects = Database.query(soql);
        System.debug('objects:::' + objects);
        return JSON.serialize(objects);
    }
    
    private static String getAllFields(String sobjectname){
           if(!Schema.getGlobalDescribe().containsKey(sobjectname)) 
            return 'Exception';
           Map<String, Schema.SObjectField> fields = Schema.getGlobalDescribe().get(sobjectname).getDescribe().SObjectType.getDescribe().fields.getMap();
        List<String> accessiblefields = new List<String>();
           for(Schema.SObjectField field : fields.values()){
               if(field.getDescribe().isAccessible())
                   accessiblefields.add(field.getDescribe().getName());
        }
        String allfields='';
        for(String fieldname : accessiblefields)
            allfields += fieldname+',';
        allfields = allfields.subString(0,allfields.length()-1);
        return allfields;
    }
}