Search code examples
yii2rbac

Yii2: Hide search results based on permission


In my table I have:

PRODUCT
id_product
name
status

Where the status assumes the following values:

1 (Active)
2 (Inactive)
3 (Archived)

In the Product index view, I want the user to see certain statuses based on the permissions. Example:

  • Administrator sees records with statuses 1, 2, and 3.
  • Moderator views: 1 and 2
  • User views: 1

How can I do this? What alternatives do I have?


Solution

  • You could add conditions to your search model (I guess you have a ProductSearch.php file) so that results will be filtered based on user's role.

    I've never used Yii's RBAC but I suppose you have a method to get user role, as described here: https://stackoverflow.com/a/25248246/4338862

    So in your search model I would add, after grid filtering conditions, one or more conditions:

    if($isUser) {     
        $query->andFilterWhere([
            'status' => 1,
        ]);
    }
    elseif($isModerator) {
        $query->andFilterWhere(['or',
           ['status' => 1],
           ['status' => 2]
        ]);
    }
    

    I can give you a more detailed answer if you need it.