I am the administrator in my website. When I register a new user, I want to add my username to new username. Such as:

my username: manager
new username: test
result: manager_test

I want to validate RESULT. I used beforevalidate() and add my username in it:

protected function beforeValidate()
{
    $this->username = Yii::app()->user->name.'_'.$this->username;
    return parent::beforeValidate();
}

but something that stored to database is: manager_manager_manager_test. In fact my program call beforevalidate in 3 times.

What shall I do? I want to read beforevalidate function once.

有帮助吗?

解决方案

You can check whether a new record to add a prefix when you create and use the "beforesave" for this.

public function beforeSave(){
    parent::beforeSave();
    if($this->isNewRecord())
        $this->username = Yii::app()->user->name.'_'.$this->username;
    return true;
}

其他提示

if(end(explode('_',Yii::app()->user->name)) != $this->username){
    $this->username = Yii::app()->user->name.'_'.$this->username;
}
return parent::beforeValidate();

Why not just do it in before save? What is the point in validating something that you know you are adding, just let validate without anything and add what you want in beforeSave.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top