Filters

Filters are one of the two types of Hooks.

They provide a way for functions to modify data of other functions. They are the counterpart to Actions.

Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output.

Add Filter Add Filter

The process of adding a filter includes two steps.

First, you need to create a Callback function which will be called when the filter is run. Second, you need to add your Callback function to a hook which will perform the calling of the function.

To add a filter to an existing tag, you will use the

Yii::app()->hooks->addFilter($tag, $callback, $priority = 10)

function, passing at least two parameters, string $tagcallable $callback.

Example:

The following code will add a filter to the ‘backend_left_navigation_menu_items‘ tag, that will execute the method of the class where this filter was added, named ‘_registerBackendMenuItem‘.

// add the menu item
Yii::app()->hooks->addFilter('backend_left_navigation_menu_items', array($this, '_registerBackendMenuItem'))

Apply Filter Apply Filter

To apply a filter use applyFilters($tag, $arg) function, passing as parameters the filter name and the variable that we want to filter

For the above added filter you will apply it using the following code at the place needed:

$menuItems = (array)Yii::app()->hooks->applyFilters('backend_left_navigation_menu_items', $menuItems);

Was this article helpful?

Related Articles