0
votes

I just recently downloaded yii2 advanced template and create new model in frontend module that extend User in "common/models" like this

class UsUser extends User
{

}

class SignupForm extends Model
{      

/**
 * Signs user up.
 *
 * @return User|null the saved model or null if saving fails
 */
public function signup()
{
    if ($this->validate()) {
        $user = new UsUser();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->save();
        return $user;
    }

    return null;
}

When I signup, there is no error and simply get redirected to main page but no data is inserted into db. I do not use public attribute in my model (either User or UsUser) as specified by Tal V. in here (Yii2 active record model not saving data . So only @property annotation in UsUser.

Maybe I am doing it wrong or is there something else to be aware of, could somebody help pointing it out? Many Thanks.

1
Your model is not validated in if condition kindly echo some test string inside if condition either use $user->save(false);AsgarAli
@Ali you are right, I think it has something to do with validation, when I put $user->save(false) as you said , it actually insert data into db. How to know which validation failed? I wonder why $this->validate() return true anyway. Sorry I just return home late from office, I should have continued to do more research.Ardeus

1 Answers

0
votes
class SignupForm extends Model
{

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if ($this->validate())
        {
            $user           = new UsUser();
            $user->username = $this->username;
            $user->email    = $this->email;
            $user->setPassword($this->password);
            $user->generateAuthKey();
            //IF UsUser MODEL IS VALID THEN SAVE DATA
            if ($user->validate())
            {
                $user->save(false);
                return $user;
            }
            //IF UsUser MODEL IS NOT VALID THEN PRINT THE ERRORS.SO YOU CAN CHECK WHAT ARE THE ERRORS IN MODEL
            else
            {
                echo "<pre>";
                print_r($user->getErrors());
                echo "</pre>";
            }
        }
    }

}