I was searching for a method to find the count of selected multi-select picklist. My aim is to select multiple options for Known-Languages in a Drop down and to display the selected count in a Counter and reflect the changes of count based on selection from multi-select picklist using Insert-Update before trigger.
But couldn't able to find a direct one and was able to see some workaround way using a List
and the split
method using ';'
and it worked well (Referred Link)
I have written my trigger as below and it worked fine with my test cases.
trigger AccountMultiselect on Account (before insert, before update) {
for(Account acc:Trigger.new){
if(String.isNotBlank(acc.Languages_Known__c)){
List<String> Langs = acc.Languages_Known__c.split(';');
acc.Counter__c = Langs.size();
} else {
acc.Counter__c = 0;
}
}
}
Can some one let me know
-
Are there any direct methods to check the count instead of
List
andsplit
? This approach was suggested somewhere 2013 and just want to know any new methods available recently. -
Does the above code have any loopholes?
Best Answer
Nope, splitting by semicolon and calling
size()
on the resulting list is pretty much it. There are probably one or two other ways (1 + # of semicolons), but the method you're using now is likely the simplest.Probably not. It's a short piece of code that uses pretty common (and standard) methods.
Generally speaking, having a good suite of unit tests is important. Having them would increase one's confidence that a piece of code will behave as expected under a variety of circumstances.
If you don't have tests that verify the following cases, I'd suggest writing tests to cover these cases:
Languages_Known__c
is null?Languages_Known__c
is empty (but not null)?Languages_Known__c
only selects one option (no semicolons)?Languages_Known__c
selects two options?Languages_Known__c
only contains semicolons?Languages_Known__c
contains duplicate selections?The second, fifth, and sixth cases shouldn't occur in normal use, but can happen if some other code is writing the value of
Languages_Known__c
(which is just a semicolon-delimited string, after all).