// 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?
CodePudding user response:
You are comparing different things so you get different results. Multiple fails here.
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.normalizeSpace()
andtrim()
- you trim the string but after splitting you don't trim the components. You don't haveSailboat
, 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?
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 togetValue()