1

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();
}
4
  • 1
    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).
    – 4uk4
    Commented Dec 15, 2021 at 20:52
  • 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.
    – liquidcms
    Commented Dec 16, 2021 at 16:12
  • +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. Commented Mar 6, 2022 at 15:42
  • If you hover over the field in the View UI, it will show you the machine name.
    – liquidcms
    Commented Mar 7, 2022 at 16:07

1 Answer 1

1

From @4k4's answer above:

foreach ($view->result as $rid => $row) {
  $type[$row->nid] = $view->field['my_views_field']->advancedRender($row)->__toString();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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