1

I am trying to determine the best way to compare values in a multiselect via apex. Goal is to create a child record when a user selects a value in the multiselect. If a user then comes back and selects another multiselect value create another record. When the user deselects a previously selected value I find the child record and update. So I need to be able to know the value that is selected and deselected. Thank you

1 Answer 1

4

Use sets. To determine what has been added, removed, or unchanged, you can use three sets, and use the various set operations (addAll, retainAll, and removeAll) to quickly determine what changes have occurred.

for(Integer index = 0; index < Trigger.size; index++) {
  Set<String> previous = new Set<String>(
    Trigger.old?.get(index).MultiSel__c?.split(';') ?? new String[0]
  );
  Set<String> current = new Set<String>(
    Trigger.new?.get(index).MultiSel__c?.split(';') ?? new String[0]
  );
  Set<String> unchanged = new Set<String>();
  unchanged.addAll(previous);
  unchanged.addAll(current);
  unchanged.retainAll(previous);
  unchanged.retainAll(current);
  previous.removeAll(current);
  current.removeAll(previous);
  // unchanged now contains values that did not change selection state
  // previous now contains all values that were deselected
  // current now contains all values that were newly selected
}

If you don't care about detecting non-changes, you can remove all lines referencing unchanged. The code above is for demonstration purposes, so feel free to modify it as you wish.

Note that this uses several new language features, namely the ?. safe navigation operator, and the ?? null-coalescing operator. You can choose to use more traditional if statements, if you prefer.

You must log in to answer this question.

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