lundi 6 mars 2017

How to check existence of data in database using Yii2?

I'm learning Yii2 and I'm trying to make a registration in my Yii basic project. The problem is that I can't check existence of some data from user input (in my case email and url) in my DB to make a unique email for every user.

public function actionRegistration()
{
    $model = new RegistrationForm();

    if ($model->load(Yii::$app->request->post()) && $model->validate())
    {           
        if (Users::findOne($model->email) !== null)//Doesn't work
            $error_email = "That email is taken. Try another.";
        if (Users::findOne($model->url) !== null)//Doesn't work
            $error_url = "That url is taken. Try another.";

        if (!(isset($error_email) || isset($error_url)))
        {
            $db = new Users();
            $db->name = $model->name;
            $db->email = $model->email;
            $db->password = $model->password;
            $db->url = $model->url;
            $db->save();
        }
        else
        {
            return $this->render('registration',
                    [
                        'model' => $model,
                        'error_email' => $error_email,
                        'error_url' => $error_url,
                    ]
                );
        }
    }
    else
    {
        return $this->render('registration',
                [
                    'model' => $model,
                ]
            );
    }
}




Aucun commentaire:

Enregistrer un commentaire