Score:2

What is the equivalent of field_view_field()?

mp flag

I am working on some code where I need to get some fields from a node. For the body, I want to display the summary, or the trimmed body if the summary is not there.

I found an example on the web using field_view_field(), which seems to do what I want it to do: return the body field using the summary_or_trimmed formatter. But it seems this is a Drupal 7 thing. I can't seem to figure out what or if there is an equivalent.

The Drupal 7 example went something like this:

$x1 =  field_view_field('node', $node, 'body', 
                                array('label'=>'hidden',
                                      'type' => 'text_summary_or_trimmed',
                                      'settings'=>array('trim_length' => 50)));

Note: I am trying to assemble text output for an email. I thought I could do this by making a custom display view mode, 'alt-teaser', that is like 'teaser' for my content type, but I don't see a way to get rid of the title (!), which I do not want. So that is why I now hope to get at individual fields, formatted.

 $viewBuilder = \Drupal::entityTypeManager()->getViewBuilder('node');
 $renderArray = $viewBuilder->view($node, 'alt_teaser');
VardeVim avatar
mp flag
Here is what worked for me (using d9) $body = $node->body[0]->view('alt_teaser'); $display = \Drupal::service('renderer')->renderPlain($body); Thank you cilefen.
Score:2
id flag

Drupal's change records usually indicate when an API has been removed or changed. This one is documented: https://www.drupal.org/node/2208327

In Drupal 8, those functions have been replaced by view() methods on, respectively, the FieldItemList object (i.e $entity->field_name, "the list of field items") and the FieldItem object (i.e. $entity->field_name[$delta], a specific item in the list). Their signatures have also been largely simplified.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.