如何使用Drupal 9中的钩子在分页视图中访问每个结果?

huangapple go评论70阅读模式
英文:

How to get access of every result in a view with pagination with a hook in Drupal 9?

问题

在Drupal 9中,我一直在尝试获取视图中每个节点结果的特定值并将它们推送到一个数组中。在调试过程中,我能够访问视图当前页面的节点,而不能访问其他页面的节点。
是否有一种方法可以通过hook_preprocess或任何其他hook来实现这一点?

我尝试过的方法:

  1. hook_preprocess_views_view中,我可以访问当前页面的节点值,但不能访问其他页面的节点值,hook_views_pre_render也是一样的。

  2. 配置视图的"每页项目数"选项为0,以在单个页面中获取所有结果,并使用hook_views_pre_viewsetItemsPerPage(10),但由于此hook在视图获取任何结果之前运行,所以无法访问任何结果。

英文:

In drupal 9, I've been trying to get a specific value of every node result from a view and push them into an array. While debugging I was able to access the nodes of the view's current page and not from the other pages.
Is there a way to achieve that with a hook_preprocess or any other hook?

Things I've tried:

  1. In a hook_preprocess_views_view I could access the node values from the page I was and not the rest, same with a hook_views_pre_render.

  2. Configured the view to Items per page option to 0 to bring me all the results in a single page and with a hook_views_pre_view to setItemsPerPage(10) but I couldn't get access to any result since this hook runs before the view fetches any.

答案1

得分: 0

要获取视图的结果,您可以在自定义模块文件中使用以下函数。

use Drupal\views\Views;

function get_view_results($view_id, $display_id) {
  $view = Views::getView($view_id);
  if (!isset($view)) {
    return [];
  }
  $view->setDisplay($display_id);
  $view->setItemsPerPage(0);

  $view->execute();
  $results = $view->result;
  return $results;
}
英文:

To get the results of a view you could use the following function in your custom module file.

use Drupal\views\Views;

function get_view_results($view_id, $display_id) {
  $view = Views::getView($view_id);
  if (!isset($view)) {
    return [];
  }
  $view->setDisplay($display_id);
  $view->setItemsPerPage(0);

  $view->execute();
  $results = $view->result;
  return $results;
}

huangapple
  • 本文由 发表于 2023年7月28日 02:49:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定