0

I'd like to display 5 different values from a custom metadata type in a lightning component. Instead of doing 5 different Apex methods, I'd like to return them all at once and then display the values where appropriate. I don't know how to "filter" results on the lightning component side - I can only find examples of displaying all the results in a list.

Helper:

       getInstitutionalMetrics : function (component, event, helper) {
    var action = component.get("c.queryAllMetrics");

    action.setCallback(this, function(response){
        component.set("v.allMetrics", response.getReturnValue());
    });
        $A.enqueueAction(action);
},

Component:

    <aura:attribute name="allMetrics" type="Metrics__mdt[]"/>

Class:

@AuraEnabled
public static List<Metrics__mdt> queryAllMetrics()
{

    List<Metrics__mdt> allMetrics = [SELECT DeveloperName, Value__c FROM Metrics__mdt 
                                                            WHERE Active__c = true];
    return allMetrics;

}

In the component, rather than displaying a list of results I need to selectively display DeveloperName A in location 1, DeveloperName B in location 2, etc. Is there a way to do this?

DeveloperName A is: <lightning:formattedText value="{!v.allMetrics.Value__c where DeveloperName='A'? }" />
0

2 Answers 2

4

You can use the reduce function to map the values into an object you can use to refer to individual elements:

action.setCallback(this, function(response){
  var results = response.getReturnValue()
   .reduce((a,v) => { a[v.DeveloperName] = v; return a; }, {});
  component.set("v.metricMap", results);
});

At that point, you can refer to the individual items by name:

<lightning:formattedText value="{!v.metricMap.A.Value__c}" />

Note that the attribute type should be a Map, not a List.

1
  • Thank you @sfdcfox. I was able to get it working with the map attribute! Appreciate the help!
    – EMC
    Apr 25, 2018 at 22:29
1

I think you should try to return a map instead of List from custom metadata Apex method i.e Map<String,Metrics__mdt>. In place of key, use DeveloperName of custom metadata type.

Then in you lightning component, you can write

DeveloperName A is: <lightning:formattedText value="{!v.allMetrics.<DEVELOPER_NAME_1>.Field_from_Custom_Metadata__c}" />

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .