How to get an action name


I am calling a function in model but i want to restrict it for certain actions in the controller.

Is there any way by which I can restrict that function by getting the action name in my model.

or any other solution for this problem.

Help me out with some specific code that i can put in my model. I know there are certain methods like getaction() but how to use it exactly.

You should avoid such a tight coupling between your model and a specific controller/action. Your model’s reusability will be very limited otherwhise. So better put such restriction into the controller.

I am using following function in model

protected function beforeSave()


   $exists = Utils::checkUserName($this->UserName);

    if ($exists)


      $this->addError("UserName",'Username already exists.');

      return false;


    return true;


In controller i want the above method to be called for ‘create’ action but not for ‘update’.

wat shud be done in this case.

You can solve this much easier: Use a unique validator in your rules(). It even takes care of the create/update case:

public function rules() {

  return array(


    array('UserName','unique','message'=>'Username already exists.'),




Thanks man…this works for now.

But if i want to call some function before save for create and not for update action then what shud i do.

bcoz i am going to add some more validations features like ‘invalid characters etc’ for checking the username in the utils file. but this is not required for update action.

Checks like these should also go into rules() as they belong to the business rules of your model. Use scenarios for the insert/update issue (read this). There are two scenarios predefined: insert and update. So you can just use a rule like this:

array('myattribute', 'match', 'on'=>'insert', 'pattern'=>'/^[a-zA-Z]*$/','message'=>'Invalid characters!'),