Question

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.

Was it helpful?

Solution

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;
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top