V
V
Valeriy Donika2015-01-09 17:10:23
Yii
Valeriy Donika, 2015-01-09 17:10:23

Yii2 user registration. Why doesn't save() work?

SiteController

public function actionSignup()
    {
        $model = new User();
        if ($model->load(Yii::$app->request->post())) {
            if ($model->validate()) {
                $model->save();
                Yii::$app->session->setFlash('signUpOk');
                return $this->refresh();
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

model User is inherited from ActiveRecords as expected.
class User extends ActiveRecord implements IdentityInterface

Why, when I submit my signup.php form, I see a flash message with a message, which indicates that I passed the validation. But, is the database empty?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Terminaft, 2015-01-09
@Terminaft

You have the wrong model. You need to create one more SignupForm model (extends yii\base\Model), and in it the fields are already validated and the User'a instance is saved to the database. See how it's done in the advanced template (registration in frontend, user model in common).

R
Roman Zhuravlev, 2015-01-09
@Zhuravljov

Something is preventing the data from being saved, perhaps the beforeSave handler in User.
Flash message, in theory, should be like this:
If the validation has already been done, there is no point in doing it again in save():
Therefore, you need to save it like this:

if ($model->validate()) {
    $model->save(false);
    //..
}

Or like this:
if ($model->save()) {
    //..
}

V
Valeriy Donika, 2015-01-09
@Valonix

Okay, I understand the advantage. Now I'll try to add ... something :)
Thank you!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question