Mohsen
Mohsen

Reputation: 1422

how create afterAction for every method of controller in yii2?

is afterAction works for every action of controller in yii2????
if not how we should make afteraction for every method of controller???

Upvotes: 0

Views: 1310

Answers (1)

arogachev
arogachev

Reputation: 33538

Yes, afterAction() event handler triggers for every action in controller.

Take a look at the official docs for this method:

This method is invoked right after an action is executed.

The method will trigger the EVENT_AFTER_ACTION event. The return value of the method will be used as the action return value.

If you override this method, your code should look like the following:

public function afterAction($action, $result)
{
    $result = parent::afterAction($action, $result);
    // your custom code here
    return $result;
}

If you need limit execution of some code for specific actions, you can use $action variable like this:

For single action:

if ($action->id == '...') {
    ...
}

For multiple actions:

if (in_array($action->id, [..., ...]) {
    ...
}

Or you can use $action->uniqueId instead.

Upvotes: 2

Related Questions