How to get label for multiselect input value in template?

Hello,

I have a blueprint containing a structure field, which contains a multiselect input. Something like this:

fields:
  items:
    label: Gegenstände
    type: structure
    columns: 
      name:
      location:
    fields:
      name:
        label: Name
        type: text
        help: Eine generische Beschreibung des Gegenstands.
        width: 1/3
      location:
        label: Lagerort
        type: multiselect
        width: 1/3
        max: 1
        options:
          storage: Lager
          office: Büro
          basement: Keller

Now, within my template I can iterate over all the structure items and call toStructure()->location(), which will give me the value of this field (so, it’s either storage, office or basement). But how can I get the correct label (e.g. Lager, Büro or Keller)?

Two options:

Simple:

Create an array map e.g. in your config

'location.options' => [
  'storage'  => 'Lager',
  'office'   => 'Büro',
  'basement' => 'Keller',
],

The when looping through the structure field:

foreach ( $page->items()->toStructure() as $item ) {
  echo option('location.options')[$item->location()->value()] ?? $item->location()->or('');
}

The alternative would be to get the value from the blueprint, see this recipe (which to me always seems overkill for something for getting a few option labels):

Thanks @texnixe for letting me know, there’s no other option. I don’t like either of the options you explained. I think the multiselect class should be able to offer this function :frowning:

1 Like