1

// I have a custom metadata object named boatNames__mdt and I'm using two methods to get a list of picklist values in a String[];

First Method

Map<String, boatNames__mdt> mapEd = boatNames__mdt.getAll();
string boatTypes = (string) mapEd.values()[0].BoatPick__c;
// BoatPick__c is a textarea field (Eg: 'Yacht, Sailboat')
string[] btWRAP = new string[]{};
**btWRAP**.addAll(boatTypes.normalizeSpace().split(','));

Second Method

string[] strL = new string[]{};
Schema.DescribeFieldResult dfr = Schema.SObjectType.boatNames__mdt.fields.BoatTypesPicklist__c;
// BoatTypesPicklist__c is a picklist field (Picklist Values: 'Yacht, Sailboat')
PicklistEntry[] picklistValues = dfr.getPicklistValues();

for (PicklistEntry pick : picklistValues){
    **strl**.add((string) pick.getLabel());
}

Map with SOQL query

Map<Id, BoatType__c> boatMap =  new Map<Id, BoatType__c>
    ([Select Id, Name from BoatType__c Where Name in :btWRAP]);

When I run the above Map with SOQL query(btWRAP[]) no records show up. But when I used it using the strl[] records do show up.

I'm stunned! Can you please explain why two identical String[] when used in exact SOQL queries behave so different?

1 Answers1

1

You are comparing different things so you get different results. Multiple fails here.

  1. mapEd.values()[0].BoatPick__c - this takes 1st element. At random. Are you sure you have only 1 element in there? You might be getting random results, good luck debugging.

  2. normalizeSpace() and trim() - you trim the string but after splitting you don't trim the components. You don't have Sailboat, you have {space}Sailboat

     String s = 'Yacht, Sailboat';
     List<String> tokens = s.normalizeSpace().split(',');
     System.debug(tokens.size());        // "2"
     System.debug(tokens);               // "(Yacht,  Sailboat)", note the extra space
     System.debug(tokens[1].charAt(0));  // "32", space's ASCII number
    

Try splitting by "comma, optionally followed by space/tab/newline/any other whitespace symbol": s.split(',\\s*'); or call normalize in a loop over the split's results?

  1. pick.getLabel() - in code never compare using picklist labels unless you really know what you're doing. Somebody will translate the org to German, French etc and your code will break. Compare to getValue()
eyescream
  • 18,088
  • 2
  • 34
  • 46
  • Thanks sir, I knew is what something not visible to the naked eye but I couldn't figure it out. Thanks for the coding best practices leson also! – Ionut Sultana Oct 08 '21 at 07:37
  • Glad I could help and thx for accepting. Technically you have 1 more option, simply edit the custom metadata and remove the space ;) But X months later you'll forget why it was written without space or another dev will come and add new value, it won't work and they won't know why... This way the code is a little more "forgiving" for what user entered. – eyescream Oct 08 '21 at 10:06