How to get rendered, rewritten field results from Drupal 8 view.

It took me a while to track this down so I wanted to post it somewhere. In the past I would have posted to api.drupal.org but it seems as though that has been rendered useless in D8 as each new release of D8 (8.3, 8.4, etc) hides the previous comments.

This was a combination of posts from Drupal Answers and elsewhere.

Drupal 7 has the function views_get_view_result(). This is useful in providing a simple method to pull a views result fields and gives the option of getting the rendered or raw value of the field. Drupal 8 also has this function but I have yet to see any documentation on how ot use it to get the rendered result (it only has id values - so, for example, if your view spits out a term name, it will only provide the tid).

Niether the D7 or D8 function provide a method to pull the fully re-written value of the field. In other words, the way the View out puts the result fo the field. This method in D8 does provide this:

<?php
$args
= [array of arguments];
$view = \Drupal\views\Views::getView('my_view');
$view->setArguments($args);
$view->setDisplay('default');
$view->execute();

foreach (
$view->result as $id => $row) {
  foreach (
$view->field as $fid => $field) {
   
$r[] = $field->advancedRender($row)->__toString();
  }
}
?>

 

This will create a 1 dimensional array of all the values for each field from each result row. Typically not what you would want as a multidimensional array would be more useful or if statement to pull out the exact field you are looking for; but those shold be easy modifications to this code.

 

Drupal Version: