문제

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