Score:1

How to get a rendered views field value programmatically?

us flag

Yes, I see there are many answers already posted here and elsewhere for this; but sadly they are all wrong. These answers include any of the following:

$view->style_plugin->getFieldValue($rid, 'field_myfield');

foreach ($view->result as $rid => $row) {
 foreach ($view->field as $fid => $field ) {
   $values[$rid][$fid . '-value'] = $field->getValue($row);
   $values[$rid][$fid . '-render'] = $field->render($row);
 }
}

$views->_entity->...

or a few others. These are all returning the field of the base entity returned by the view. These are entity field values. These are not the "fields of the view".

I know how to access these in a twig template (views-view-fields--[viewname]--[displayname].html.twig) but haven't been able to find out how to do this in a custom module.

Answer:

From @4k4's tip below:

This works:

foreach ($view->result as $rid => $row) {
  $type[$row->nid] = $view->field['my_views_field']->advancedRender($row)->__toString();
}
4uk4 avatar
cn flag
*These are not the "fields of the view"* - `$view->field` contains the fields you have configured in the FIELDS section of the View. Each field is a field handler plugin and if you want to render a field exactly like it is configured in the View then use the plugin method advancedRender($row).
liquidcms avatar
us flag
I had tried advancedRender() (even though didnt include it in my list above); but must have been applying to the wrong thing. This does work. Thank you. I've added full answer to the post.
cn flag
+1 upvote on your question, @liquidcms, thank you. You should enter your above answer as the answer below, in the text input box below "Your Answer" on this answer and then tick it to mark it as the accepted answer. I found your answer useful. One thing I would want to find easily is the machine name of the field in the views row - in the views edit screen in the web admin pages, it displays the name "e.g. Content: ID" but not the machine name ("nid"). Thanks again.
liquidcms avatar
us flag
If you hover over the field in the View UI, it will show you the machine name.
Score:0
us flag

From @4k4's answer above:

foreach ($view->result as $rid => $row) {
  $type[$row->nid] = $view->field['my_views_field']->advancedRender($row)->__toString();
}
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.