Execute my code before any action of any controller

yii2 before action
yii2 redirect

I would like to check if my user have filled certain fields in his profile before he can access any action of any controller. For example

if(empty(field1) && empty(field2))
{
   header("Location:/site/error")
}

In yii1 I could do it in protected\components\Controller.php in init() function But in yii2 I'm not sure where to put my code. I cannot modify core files, but not sure what to do in backend of my advanced application to make it work.

I know I can user beforeAction() but I have too many controllers to do that and to keep track of every controller

In case you need to execute a code before every controller and action, you can do like below:

1 - Add a component into your components directory, for example(MyGlobalClass):

namespace app\components;
class MyGlobalClass extends \yii\base\Component{
    public function init() {
        echo "Hi";
        parent::init();
    }
}

2 - Add MyGlobalClass component into your components array in config file:

'components' => [
    'MyGlobalClass'=>[
        'class'=>'app\components\MyGlobalClass'
     ],
     //other components

3 - Add MyGlobalClass into bootstarp array in config file:

'bootstrap' => ['log','MyGlobalClass'],

Now, you can see Hi before every action.

Please note that, if you do not need to use Events and Behaviors you can use \yii\base\Object instead of \yii\base\Component

How to use a component before every action of a controller, I guess this is a tip on how to execute some code before every action in Almost done, now use the component in as many Controllers as you  In a base controller, you can override Controller.OnActionExecuting(context) which fires right before the action executes. You can set context.Result to any ActionResult (such as RedirectToAction) to override the action. Alternatively, you can create an ActionFilterAttribute, and exactly like above, you override the OnActionExecuting method. Then, you just apply the attribute to any controller that needs it.

Just add in config file into $config array:

    'on beforeAction' => function ($event) {
           echo "Hello";
    },

Code before a controller's action is executed?, Good news: there's no need to rewrite preDispatch! There is dynamic eventing that is fired both before and after the dispatch: An excerpt of  Is there any way to execute a method in a controller before any action is called automatically? For example, let's say I have the login credentials of the user stored in cookies, I have a user controller and any time any of the actions in that controller is called I wanna check if the user is logged in or not.

Create a new controller

namespace backend\components;
class Controller extends \yii\web\Controller {
    public function beforeAction($event)
    {
        ..............
        return parent::beforeAction($event);
    }
}

All your controllers should now extend backend\components\Controller and not \yii\web\Controller. with this, you should modify every controller. I would go for this solution.

I believe you might also replace 1 class with another (so no change to any controller necessary), something like

\Yii::$classMap = array_merge(\Yii::$classMap,[
                '\yii\web\Controller'=>'backend\components\Controller',
            ]);

See more details here: http://www.yiiframework.com/doc-2.0/guide-tutorial-yii-integration.html and I took the code from here: https://github.com/mithun12000/adminUI/blob/master/src/AdminUiBootstrap.php

you can put this in your index.php file. However, make sure you document this change very well as somebody that will come and try to debug your code will be totally confused by this.

ASP.NET Model View Controller 5 Advanced Training, In this example, every method in the customer controller would require So, if you need some code to be executed, either before an action is executed or after,​  When using Url.Action, the current route values for controller and action are specified for you - the value of controller and action are part of both ambient values and values. The method Url.Action , always uses the current values of action and controller and will generate a URL path that routes to the current action.

Just i think this code on config file can help you:

'on beforeAction' => function ($event) {
      // To log all request information
},
'components' => [
    'response' => [
        'on beforeSend' => function($event) {
            // To log all response information
        },
    ],
];

Controllers, An action is any public method in a controller with the Action suffix. initialize() method (if present) first, before any action is executed on a controller. we showed code in only one action, which will be executed with the appropriate request. The code that runs after the response is very much related to the action and is based on calculations performed in the action. It is the action's responsibility to execute the additional code after the response has been delivered. I tried to use the middleware pattern by adding the following code in my Configure method of my Startup clas:

Or, https://github.com/yiisoft/yii2/blob/master/docs/guide/security-authorization.md use RBAC, to restrict access to controllers actions one at a time based on rules. Why would you want to restrict access to controller actions based on user fields is beyond me. You will not be able to access anything (including the login form) if you put a restriction there.

Ruby on Rails for Microsoft Developers, end end An around filter will typically invoke the execution of the action, but this is them, so that all the code before the execution of the action is executed in the order it and then an unnamed filter that uses a block: def ExampleController  Action Controller OverviewIn this guide you will learn how controllers work and how they fit into the request cycle in your application.After reading this guide, you will know: How to follow the flow of a request through a controller. How to restrict parameters passed to your controller. How and why to store data in the session or cookies. How to work with filters to execute code during

How to Create a Custom Action Filter in ASP.NET MVC, When we enable a filter across all controllers or actions, the filter enables the Have you ever come across source code as shown in the image below? [​Authorize] is an Authorization filter, and it gets executed before any HTPP The Authentication filter runs before any other filter or action method; The  It provides the following methods to execute a specific logic after and before controller action's execution: OnActionExecuting(ActionExecutingContext filterContext): Just before the action method is called. OnActionExecuted(ActionExecutedContext filterContext): After the action method is called and before the result is executed (before view render).

Handle requests with controllers in ASP.NET Core MVC, An action (or action method) is a method on a controller which handles requests. A controller is an instantiable class in which at least one of the following conditions is true: return BadRequest(); produces a 400 status code when executed. To perform logic before or after an action method, use a filter. Create a custom action filter in ASP.NET Core MVC. You can take advantage of custom action filters to execute reusable code before or after the execution of an action method.

The Definitive Guide to Catalyst: Writing Extensible, Scalable and , An action class is a type of Catalyst::Controller that uses the bottom-level want code execution to then proceed up the call stack back to Catalyst::Action and then to execute { my $self = shift; my ($controller, $c) = Q_; # do stuff before parent  If you want to redirect the user from one controller action to another, you call the RedirectToAction() method. For example, the Details() action in Listing 3 either displays a view or redirects the user to the Index() action depending on whether the Id parameter has a value.

Comments
  • @MiskoMali Do you use modules?
  • Another thing, do you need to interact with forms? or you need to just execute some code before every controller's action? in case of forms, if you use a model, you can use beforeValidate()
  • @MiskoMali Well, if you use module, you can write your code in init() method which will be executed before each controller of that module
  • I just need to execute some code before every action, not related to any forms or database. I'm using modules in vendor folder, not in backend folder. In backend folder I'm using only Controller and Models
  • @MihaiP. No dear, This is just a class (component, object, event or behavior) which will be initiated in application bootstrap. As soon as application runs, this class's init() method will be called.
  • This one is the best for handling 'global' beforeAction event.
  • yes it's very good and I think so it would be the best answer !