如何使用模块修改Drupal 7.x中视图的输出

时间:2016-08-22 22:23:21

标签: mysql drupal module drupal-7 drupal-views

我想修改正在运行的查询,以便在视图中创建一个表但是很难,所以为了保持简单,我使用的是一个只列出表中用户的普通视图,我正在尝试修改查询使表有两列。我一直在查看Drupal查询的文档,试图找到教程,并查看关于其他人如何在Drupal和Views中修改查询的博客帖子,但到目前为止还没有人工作或展示过如何做这么简单的事情,或者我和#39;我试图按照他们所做的事情创建简单的查询语句而没有结果。

我主要尝试使用hook_views_pre_execute(),但也试过了。这就是我的代码目前的样子:

<?php
/**
 * Implements hook_views_query_alter().
 */
// This function is called right before the execute process.
function my_module_views_pre_execute(&$view) {
    if ($view->name == 'page' && $view->current_display == 'page') { //checks name of the view and what type it is
        drupal_set_message("I can make changes to the view here.."); //diagnostic information, shows we can make changes to that view
        $query =db_select('node','n')//select base table, alias is n.
            ->fields('n',array('nid', 'title', 'created', 'uid')); //adding fields nid, title, created, uid.
        dpm($query->execute()->fetchAll()); // diagnostic information, shows whats being returned by the query 
        $query->execute()->fetchAll();

        $view->build_info['query'] = $query;
    }
}

我可以使用drupal_set_message("I can make changes to the view here..");在视图上创建一条消息,并在“视图设置”标签中启用“显示SQL查询”#39并且它的输出是来自我的模块/代码的查询(它与视图创建的表不匹配)。

那为什么它根本不影响表格输出呢?如何修改正在运行的查询以显示视图(这显然与“显示SQL查询&#39;输出”不同?)

1 个答案:

答案 0 :(得分:1)

我在这里仅举例说明了nid我可以为你提供一个改变视图输出的想法。

/**
 * 
 * @param type $view
 * @param type $query
 * Implements hook_views_query_alter(). This function is Used when we need to Alter the query before executing the query.
 */
function mymodule_views_query_alter(&$view, &$query) {
    if ($view->name == 'VIEW_NAME' && $view->current_display == 'PAGE_NAME') {
    drupal_set_message("I can make changes to the view here.."); //diagnostic information, shows we can make changes to that view
        $query =db_select('node','n')//select base table, alias is n.
            ->fields('n',array('nid', 'title', 'created', 'uid')); //adding fields nid, title, created, uid.
        dpm($query->execute()->fetchAll()); // diagnostic information, shows whats being returned by the query 
        $result = $query->execute()->fetchAll();
    $nids = array();
    foreach ($result as $value) {
      $nids[] = $value->nid;
     }
    $view->query->where[1]['conditions'][] = array('field' => "node.nid", "value" => $nids, "operator" => "IN");
  }
}

hook_views_pre_execute()在查询构建过程中为时已晚,所以我认为你应该使用hook_views_query_alter()。

由于