2011-08-02 73 views
0

我在我的drupal站點中有幾個主持人角色。具有此角色的用戶可以創建名爲News的特定內容類型的內容。讓我們將角色稱爲以下角色:role_a,role_b,role_c,...Drupal:在視圖中使用查詢字符串數據

現在我有一個視圖,顯示最近5個新聞元素。

我的問題是如何根據查詢字符串來查看View中的News元素? 我的意思是在頁面http://mysite.com/a我想只看到用戶使用「a」角色添加的新聞。 http://mysite.com/b適用於「b」型用戶。等等

我如何在視圖過濾器中使用查詢字符串參數?

回答

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; 
     } 
    } 
    } 
} 

因此,舉例來說,如果您的網址是http://mysite.com/a,那麼它會查找角色ID「A」,然後通過與該角色的作者找到的所有節點。它也將採用實際的角色ID - 例如,如果角色'a'的ID是10,那麼http://mysite.com/10也會返回相同的結果。

如果您只想查找角色名稱,您可以修改掛鉤在未找到角色時失敗(只需使$ rid = 0並且不應得到任何結果)。

0
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; 
     } 
    } 
    } 
}