Yii2 ActiveForm issue

I have a update user form with fields such as username, email, password, etc. I need the password field to be empty and to update the users.password field in the MySQL database only when the user has filled in the password field. Is it possible? I use the ActiveForm widget of Yii2.

Upvotes: 0

Views: 144

Answers (1)

Akshay Vanjare
Akshay Vanjare

Reputation: 655

First of all, it's not an Yii2 ActiveForm issue. It can be possible by following some simple steps.

Create two variables in your model, one for storing password, and another is for repeat password field.

public $REPEAT_PASSWORD;
public $INIT_PASSWORD;

then add afterFind function to set null value to your password field, so it wont be shown to user

    public function afterFind()
{
    //reset the password to null because we don't want password to be shown.
    $this->INIT_PASSWORD = $this->PASSWORD;
    $this->PASSWORD = null;

    parent::afterFind();
}

and now, write beforeSave function to save user password if user has entered on

    public function beforeSave()
{
    // in this case, we will use the old hashed password.
    if(empty($this->PASSWORD) && empty($this->REPEAT_PASSWORD) && !empty($this->INIT_PASSWORD)) {
        $this->PASSWORD=$this->REPEAT_PASSWORD=$this->INIT_PASSWORD;
    }   elseif(!empty($this->PASSWORD) && !empty($this->REPEAT_PASSWORD) && ($this->PASSWORD == $this->REPEAT_PASSWORD))   {
        $this->PASSWORD = md5($this->PASSWORD);
        $this->REPEAT_PASSWORD = md5($this->REPEAT_PASSWORD);
    }

    return parent::beforeSave();
}

Upvotes: 1

Related Questions