0

This is the example array I get sent from the CMS to Smarty.

[field] => Array
(
    [value] => 19
    [options] => Array
        (
            [labels] => Array
                (
                    [0] => --- Select ---
                    [1] => John
                    [2] => Mark
                    [3] => Luke
                    [4] => Philip
                )

            [values] => Array
                (
                    [0] => 
                    [1] => 15
                    [2] => 1
                    [3] => 19
                    [4] => 17
                )

        )

So I would normally write {$field.value} or {html_options values=$field.options.values output=$field.options.labels selected=$field.value}

My question is how can I easily get the label from the value. I tried this: {$field.options.labels[$field.value]} but then realise this is just going to get the index of the array and not the value.

I know you could do this in a {foreach/if} but that is going to get messy in the template. Is there a way to write a plugin for this?

John Magnolia
  • 16,769
  • 36
  • 159
  • 270
  • I'm not sure but something like this could work `{html_options values=array_combine(array_values($field.options.values),array_values($field.options.labels))}` – sofl Sep 21 '12 at 23:48

1 Answers1

1

Without foreach loop it can be done in one-liner:

{$field.options.labels[$field.value|array_search:$field.options.values]}

Or modifier:

function extractLabel($field){
    $idx = array_search($field['value'], $field['options']['values']);
    if($idx !== FALSE && isset($field['options']['labels'][$idx])){
        return $field['options']['labels'][$idx];       
    }
}

$smarty->registerPlugin('modifier', 'extractLabel', 'extractLabel');

tpl:

{$field|extractLabel}
dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85