0

If I have a news site where I can select a source e.g. a press agency (given by a Taxonomy field) when creating a new article, how can I put this source at the beginning of the article text when viewing it? Like this:

(SOURCE) Beginning of article blabla............................

I already found a solution by using three different custom templates for getting rid of all the html wrappers and then floating the article text around (SOURCE), but there must a better solution like manipulating the node array or sth?

2

You can combine two fields in hook_ENTITY_TYPE_view()

function mymodule_node_view(&$build, $entity, $display, $view_mode) {

  if (isset($build['field_source'][0]['#markup']) && isset($build['body']['0']['#text'])) {

    $build['body']['0']['#text'] =
      '<strong>(' . $build['field_source'][0]['#markup'] . ')</strong> ' .
      $build['body']['0']['#text'];

    unset($build['field_source']);

  }
}

and unset the added field to avoid double content.

You can also add html tags if they are allowed in the text format.

This is an example. You have to look into the build array after you've configured the display mode in ui and adjust the array keys.

3
  • This looks great! Is it possible to implement this also as a preproccess in the .theme file?
    – 0711master
    Dec 30 '16 at 14:30
  • 1
    Yes, this should be possible. But it is better to do it earlier in the entity view hook, because then the changes are visible in other places like search and the admin theme.
    – 4k4
    Dec 30 '16 at 14:37
  • There's a fairly simple trick to get rid of wrapping template/markup for a field in your template, just access the first delta directly: {{ content.source.0 }} {{ content.text.0 }}. Only works so easily if you have a single delta, but looks ike that's true for both of your fields
    – Berdir
    Dec 30 '16 at 22:27
1

I think you have done it the correct way...

You could also use a preprocess function to add the 'float:right' style when your field is displayed:

function your_module_preprocess_field(&$vars) {
   $element = $vars['element'];
   $fn = $element['#field_name'];
   switch ($fn) {
      case 'field_your_source_field':
         $vars['attributes']['style'][]='float:left';
      break;
   }
}

This is maybe more clean to add a class the same way:

 $vars['attributes']['class'][] = 'your--float-left-class';

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.