Controller filter example

Hello Guys,

I’m new to yii and i need to implement filters in some of my classes but the online documentation does not provide examples. This is what I want to do: I have a User controller with the following methods index, create, update, admin.

I want to create a beforeFilter that does some action before executing the index and admin actions. I also want to create another filter that runs before the create and update action. In summary, I need 2 filters, one that applies to the index and admin actions and another one that applies to the create and update action.

I do not seem to be able to get this to work. Any help or sample code or link to a tutorial or resource on this subject will be greatly appreciated.

Since you have not to implement code for all undefined actions,

why don’t you implement your code in specific methods?

That would not be efficient because I want to apply the same set of logic in different actions in different controllers.

For example, I want to be able to check that only a user that has a role of clerk can access this controller/action: user/admin, user/report, user/call etc. Also I want the same logic implemented in the following controllers/action employee/admin, employee/report etc

The best way is to use a filter. I do not understand how to write different filters that would apply to different controller actions

Have you tried beforeAction method?

I think you are really looking for an RBAC solution. You can check the guide here. Or if you want something simpler, you can use my Super Simple RBAC tutorial, which uses behaviors. Your access control and RBAC needs are likely to grow over the life of your project and it might make more sense to dig in and go in that direction in the first place. Hope that helps.

Thanks a lot Fabrizio and evercode. I’d like to ask if there are any RBAC extensions for Yii2

I know yii-admin ( ), but in my opinion Rights available for Yii 1 was the top.