John
John John has been developing websites and software for over 20 years. Focusing on Drupal over the last 12 years.

Drupal 8: Programmatically get data from a view field

Drupal 8: Programmatically get data from a view field

Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

Viewfield Project on drupal.org

When working on a recent project they were using the Viewfield contrib module to allow the option to render a view display as a field.

use Drupal\views\Views;

// Firstly, get the view in question.
$view = Views::getView('view_machine_name');

// Set which view display we want.
$view->setDisplay('view_display_name');

// Pass any arguments that the view display requires.
$view->setArguments([$entity->id()]);

// Execute the view.
$view->execute();
$view_result = $view->result;

// Access field data from the view results.
foreach ($view_result as $data) {
  $entity = $data->_entity;
  $title = $entity->getTitle();
  $body = $entity->get('body')->value;
  
  // Do whatever you want with the data.
}

This is a quick summary of what I did to dig into the viewfield and retrieve the field data from the output. If there is a cleaner more efficient way to achieve this then please leave a comment below.

comments powered by Disqus