-1

I have a soql query to get custom metadata value with where condition. But to avoid the SOQL query, i would like to replace SOQL with getInstance() method to get the custom metadata values but i wanted to filter the data with where condition. Can you please suggest me how to do? Pls advice

Existing SOQL: 
 public static String getMetaValue(String CmpName, String CmpType, String MName, String FieldName) 
 
   {
        for(CodeSetting__mdt codeset: [select FieldName__c, Value__c from CodeSetting__mdt 
        where CName__c =: CmpName and Type__c =: CmpType and Method__c =: MName]){
            if(codeset.FieldName__c == FieldName && codeset.Value__c != null){
                return codeset.Value__c;
            }
        }
        
        return '';
    }

enter image description here

3
  • why do you want to avoid the SOQL query? see this Q&A
    – cropredy
    Jun 10, 2022 at 1:37
  • unless you are querying long text fields, you have unlimited soql queries - see help.salesforce.com/s/…
    – cropredy
    Jun 10, 2022 at 4:02
  • Queries are counting and throwing the limit exceeds exception. I debug the exceed issue and saw that these queres are counted to reach the limit. I read in the document that if the metadata has LongTextArea, it will count. I upload the image in the question area.
    – RKCY
    Jun 10, 2022 at 4:08

1 Answer 1

2

Given that your SOQL query uses text area (long) fields, then each query counts against your SOQL limits.

You have a couple of options:

Option 1

Refactor your logic so rather than looping to call getMetaValue 41 times; instead call it once with collections of filters so you can use SOQL IN operator, store the results in a static map and then process the map via Apex. In effect, bulkify your call to the MDT.

Option 2

If you don't have that many MDT rows, refactor your code to retrieve all of the MDT into one or more maps and write accessors on those maps to handle your looped queries (essentially cache the values).

You can do this with either SOQL or the getAll() method

Note, there is no option to use filters with getInstance() which retrieves only single rows if you know the ID or DeveloperName of that row.

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