1

I have a field (list integer) and I would like to render its keys and values. I found field.html.twig but within I only have access to item.content which is the value. I would also like to access the key. I also had a look to theme_preprocess_field(&$variables) but I'm not able to get the correct keys.

I tried

  foreach ($variables['items'] as $key => $item) {
    $variables['items'][ $key ]['key'] = $key;
  }

Unfortunatelly this only gives me the array positions 0,1,2 ... But I would like to have the actual keys from my list, i.e.

100|red 200|green 300|blue 400|black ...

0

Here is how you can get the list field key and value

function themename_preprocess_field(&$variables, $hook) {

    if ($variables['field_name'] == 'field_test') {

        foreach ($variables['items'] as $key => $item) {
            $list_field_value = $item['content']['#markup'];
            $list_field_key = $variables['element']['#items'][$key]->getString();
        }

    }

}

Note: replace field_test with the actual field machine name, do not replace field_name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.