Search code examples
drupal-6view

Drupal: using query string data in Views


i have several moderator roles in my drupal site. the users with this roles can create content of specific content-type called News. let's call the roles the following: role_a, role_b, role_c, ...

now i have a View that shows the last 5 News elements.

my question is how to granulate the News elements in View according to the query string? i mean on page http://mysite.com/a i want to see only the news that was added by the user with the "a" role. http://mysite.com/b is for the "b"-roled user. etc.

how can i use the query string parameters in the Views filter?


Solution

  • I think you mean you want to use an Argument, rather than the query string. In any case, I don't think Views can handle rolenames by default (it can handle role IDs just fine), so you'll have to modify your view query in order to achieve what you want.

    First, add User: Roles as an argument in your View. Then, in a custom module, implement hook_views_query_alter() and modify the query by replacing the rolename with its role 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;
          }
        }
      }
    }
    

    So, for example, if your url is http://mysite.com/a, then it will look up the ID of role 'a', then find all nodes by an author with that role. It will also take the actual role ID - for example, if the ID of role 'a' is 10, then http://mysite.com/10 will also return the same result.

    If you want it only to look up rolenames, you can modify the hook to fail when it doesn't find the role (just make $rid = 0 and you shouldn't get any results).