How to apply a beforeFilter to certain actions only

If you define a beforeFilter in your controller, it will be executed before each action. Sometimes, that behaviour is not desired, and you want to exclude an action from the application of the beforeFilter. The following simple example gives you an idea of how to accomplish that:

// app/controllers/users_controller.php
class UsersController extends AppController
{
    function beforeFilter()
    {
        if ($this->action != 'login')
        {
            // execute beforeFilter logic
        }
    }

    function login()
    {
        // do login
    }

    function edit($id)
    {
        // do edit
    }

    function delete($id)
    {
        // do delete
    }
}

2 Comments

  1. Posted August 4, 2006 at 8:38 am | Permalink

    Useful stuff thanks. Is there a similar way to stop custom functions (especially beforeSave()) from being called in your model?

  2. JP
    Posted August 7, 2006 at 8:12 pm | Permalink

    something I use in my controllers…
    function beforeFilter(){
    $excludeBeforeFilter = array(‘view’,’index’);
    if (!in_array($this->action,$excludeBeforeFilter)){
    $this->checkSession();
    }
    }
    Just add any other actions you want to exclude from validation to the array.


%d bloggers like this: