Drupal - How add markup and prefix / suffix for computed field
I don't know where your variable $entity_field_item
comes from, but you can generally add additional markup in at least three different ways:
1. Adding #prefix
and #suffix
to the fields render array using a preprocess function:
function mytheme_preprocess_field(&$variables, $hook) {
$element = $variables['element'];
if ($element['#field_name'] == 'field_myfield') {
$variables['items'][0]['#prefix'] = '<div class="row">';
$variables['items'][0]['#suffix'] = '<span class="suffix">Count</span></div>';
}
}
2. Adding #prefix
and #suffix
in hook_node_view()
:
$node->content['field_myfield'][0]['#prefix'] = '<div class="row">';
$node->content['field_myfield'][0]['#suffix'] = '<span class="suffix">Count</span></div>';
3. Adding a new item to the $content
array:
$node->content['my_custom_output'] = array(
'#type' => 'markup',
'#markup' => $entity_field_item['value'],
'#prefix' => '<div class="row">',
'#suffix' => '<span class="suffix">Count</span></div>',
);
Drupal 8
This example simply creates a new markup object from the original text value:
use Drupal\Core\Render\Markup;
/**
* Implements template_preprocess_field__FIELD_NAME().
*/
function MYTHEME_preprocess_field__MYFIELD(&$variables) {
$original_value = $variables['items'][0]['content']['#text'];
$variables['items'][0]['content'] = Markup::create('<h1>' . $original_value . '</h1>');
}
You may want to check what's inside $variables['items'][0]['content']
first. As it absolutely depends on the field type and its formatter where the original value can be found:
- maybe
$variables['items'][0]['content']['#text']
- maybe
$variables['items'][0]['content']['#markup']
- maybe
$variables['items'][0]['content']['#template']
- ...
This example simply adds some markup on top of the field output:
/**
* Implements template_preprocess_field__FIELD_NAME().
*/
function MYTHEME_preprocess_field__MYFIELD(&$variables) {
$variables['content']['#prefix'] = '<div class="linkbox-title"><span></span>' . t('Links') . '</div>';
}
This example wraps the output of every item of a multi-value field:
use Drupal\Core\Render\Element;
/**
* Implements template_preprocess_field__FIELD_NAME().
*/
function MYTHEME_preprocess_field__MYFIELD(&$variables) {
$element = $variables['element'];
$items = Element::children($element);
foreach ($items as $key) {
$variables['items'][$key]['content']['#prefix'] = '<div class="MYCLASS item-' . $key . '">';
$variables['items'][$key]['content']['#suffix'] = '</div>';
};
}
If you are using a preprocess function (which would be my choice), you will want to account for the possibility of more than one item in the field:
function mytheme_preprocess_field(&$variables) {
if($variables['element']['#field_name'] == 'field_my_field'){
foreach($variables['items'] as $key => $item){
$variables['items'][ $key ]['#prefix'] = '<div class="row">';
$variables['items'][ $key ]['#prefix'] = '<span class="suffix">Count</span></div>';
}
}
}