【问题标题】:Drupal: using query string data in ViewsDrupal:在视图中使用查询字符串数据
【发布时间】:2011-08-02 09:57:56
【问题描述】:

我在我的 drupal 站点中有多个版主角色。具有此角色的用户可以创建称为新闻的特定内容类型的内容。我们将角色命名为:role_a、role_b、role_c、...

现在我有一个显示最后 5 个新闻元素的视图。

我的问题是如何根据查询字符串来细化 View 中的 News 元素? 我的意思是在页面http://mysite.com/a 我只想看到由具有“a”角色的用户添加的新闻。 http://mysite.com/b 适用于“b”角色的用户。等等

如何在视图过滤器中使用查询字符串参数?

【问题讨论】:

    标签: drupal-6 views


    【解决方案1】:

    我认为你的意思是你想使用一个参数,而不是查询字符串。无论如何,我不认为 Views 可以默认处理角色名称(它可以很好地处理角色 ID),因此您必须修改您的视图查询才能实现您想要的。

    首先,在视图中添加用户:角色作为参数。然后,在自定义模块中,实现 hook_views_query_alter() 并通过将角色名称替换为其角色 ID 来修改查询。

    function MYMODULE_views_query_alter(&$view, &$query) {
      if ($view->name == 'my_view') {
        $rolename = '';
        foreach ($query->where as $where_index => $where) {
          // find the role ID clause
          $clause_index = array_search('users_roles.rid = %d', $where['clauses']);
          if ($clause_index !== FALSE) {
            // found it, so get the rolename
            $rolename = $where['args'][$clause_index];
            break;
          }
        }
        // if the rolename argument was found
        if (!empty($rolename)) {
          // get the role ID
          $user_roles = user_roles();
          $rid = array_search($rolename, $user_roles);
          // if the role exists, then replace the argument
          if ($rid !== FALSE) {
            $query->where[$where_index]['args'][$clause_index] = $rid;
          }
        }
      }
    }
    

    因此,例如,如果您的 url 是http://mysite.com/a,那么它将查找角色“a”的 ID,然后查找具有该角色的作者的所有节点。它还将采用实际的角色 ID - 例如,如果角色“a”的 ID 为 10,则 http://mysite.com/10 也将返回相同的结果。

    如果您只希望它查找角色名称,您可以修改钩子以在未找到角色时失败(只需使 $rid = 0 并且您不应该得到任何结果)。

    【讨论】:

      【解决方案2】:
      function MYMODULE_views_query_alter(&$view, &$query) {
        if ($view->name == 'my_view') {
          $rolename = '';
          foreach ($query->where as $where_index => $where) {
            // find the role ID clause
            $clause_index = array_search('users_roles.rid = %d', $where['clauses']);
            if ($clause_index !== FALSE) {
              // found it, so get the rolename
              $rolename = $where['args'][$clause_index];
              break;
            }
          }
          // if the rolename argument was found
          if (!empty($rolename)) {`enter code here`
            // get the role ID
            $user_roles = user_roles();
            $rid = array_search($rolename, $user_roles);
            // if the role exists, then replace the argument
            if ($rid !== FALSE) {
              $query->where[$where_index]['args'][$clause_index] = $rid;
            }
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-08
        • 1970-01-01
        • 1970-01-01
        • 2020-09-13
        • 1970-01-01
        • 2017-01-10
        • 1970-01-01
        相关资源
        最近更新 更多