Score:1

How to programmatically load a View?

om flag

I have created a View that I want to fetch the output from within a module. On drupal.org, the latest recommendation seems to be

$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load(1)

So, this is my code.

/** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
$view = \Drupal::entityTypeManager()
  ->getStorage('view')
  ->load($view_id);
$view->getDisplay('latest_blog');

It seems to be getting me very close - in debug, I'm seeing properties that clearly indicate I'm getting the object.

Am I on the right track and just missing one little piece? Loading a taxonomy term, or a node is easy. But this View thing is stumping me and I can't find anything much beyond the old Drupal 7 way of doing this.

Les Lim avatar
us flag
Getting the output of an entity is probably rendering the entity. Generally, *loading* is used to only mean *fetching an entity from its storage*.
sea26.2 avatar
om flag
@LesLim I disagree... A search for that (which I did, incidentally) will show how to "render" the view. That is not what I want. The answer using the same context yields the results I would expect for a node. The same, it seems, should apply to a View.
Les Lim avatar
us flag
Then I suppose I'm not sure what you're expecting to see on the loaded entity, that you're not seeing.
Score:3
cn flag

You probably want to load a ViewExecutable:

class ViewExecutable

Represents a view as a whole.

An object to contain all of the data to generate a view, plus the member functions to build the view query, execute the query and render the output.

$executable = $view->getExecutable();
Score:2
om flag

Thank you @4x4. I dug around core and also found that. My working code that produces the resulting node from the query is this.

  $view = \Drupal::entityTypeManager()
    ->getStorage('view')
    ->load($view_id)
    ->getExecutable();

  // Get the NID from the View result.
  $view->initDisplay();
  $view->setDisplay('latest_blog');
  $view->execute();
  $result = $view->result;

With the NID from that, we can easily get the path - which was what I needed.

No Sssweat avatar
ua flag
If you just wanted to the result, a little shortcut [views_get_view_result](https://api.drupal.org/api/drupal/core%21modules%21views%21views.module/function/views_get_view_result/9.3.x)
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.