Need help in registering users

Hi, I’m making registration on Yii2 but User class doesn’t write anything to database.

Here is my code:





<?php

namespace frontend\models;


use common\models\User;

use yii\base\Model;

use Yii;


/**

 * Signup form

 */

class SignupForm extends Model

{

    /**

     * Signs user up.

     *

     * @return User|null the saved model or null if saving fails

     */

    public function signup()

    {

        if( ! $data = Yii::$app->request->post('User'))


            return false;


        $user = new User();

        $user->setScenario($user::SCENARIO_SIGNUP);


        $user->username = $data['username'];

        $user->email = $data['email'];

        $user->phone = $data['phone'];

        $user->password = $data['password'];

        $user->rules = $data['rules'];


        if ($user->validate())

        {

            $user->generateAuthKey();

            $user->save();

//            dump($user->getErrors());

        }


        return $user;

    }

}


// Controller: 


<?php

namespace frontend\controllers;


use Yii;

use common\models\LoginForm;

use frontend\models\PasswordResetRequestForm;

use frontend\models\ResetPasswordForm;

use frontend\models\SignupForm;

use frontend\models\ContactForm;

use yii\base\InvalidParamException;

use yii\web\BadRequestHttpException;

use yii\web\Controller;

use yii\filters\VerbFilter;

use yii\filters\AccessControl;


/**

 * Site controller

 */

class SiteController extends Controller

{

    /**

     * @inheritdoc

     */

    public function behaviors()

    {

        return [

            'access' => [

                'class' => AccessControl::className(),

                'only' => ['logout', 'signup'],

                'rules' => [

                    [

                        'actions' => ['signup'],

                        'allow' => true,

                        'roles' => ['?'],

                    ],

                    [

                        'actions' => ['logout'],

                        'allow' => true,

                        'roles' => ['@'],

                    ],

                ],

            ],

            'verbs' => [

                'class' => VerbFilter::className(),

                'actions' => [

                    'logout' => ['post'],

                ],

            ],

        ];

    }


    /**

     * @inheritdoc

     */

    public function actions()

    {

        return [

            'error' => [

                'class' => 'yii\web\ErrorAction',

            ],

            'captcha' => [

                'class' => 'yii\captcha\CaptchaAction',

                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,

            ],

        ];

    }


    /**

     * Logs in a user.

     *

     * @return mixed

     */

    public function actionLogin()

    {

        if (!\Yii::$app->user->isGuest) {

            return $this->goHome();

        }


        $model = new LoginForm();


        /*$model->load(Yii::$app->request->post());

        dump($model);*/


        if ($model->load(Yii::$app->request->post()) && $model->login()) {

            return $this->goBack();

        } else {

            return $this->render('login', [

                'model' => $model,

            ]);

        }

    }




    /**

     * Logs out the current user.

     *

     * @return mixed

     */

    public function actionLogout()

    {

        Yii::$app->user->logout();


        return $this->goHome();

    }


    /**

     * Signs user up.

     *

     * @return mixed

     */

    public function actionSignup()

    {

        $model = new SignupForm();


        $user = $model->signup();


        if ($user && !$user->getErrors()) {

            if (Yii::$app->user->login($user, 0)) {

                return $this->goHome();

            }

        }


        return $this->render('signup', [

            'model' => new \common\models\User,

            'mess_error' => $user ? $user->getErrors() : null,

        ]);

    }


    /**

     * Requests password reset.

     *

     * @return mixed

     */

    public function actionRequestPasswordReset()

    {

        $model = new PasswordResetRequestForm();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            if ($model->sendEmail()) {

                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');


                return $this->goHome();

            } else {

                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');

            }

        }


        return $this->render('requestPasswordResetToken', [

            'model' => $model,

        ]);

    }


    /**

     * Resets password.

     *

     * @param string $token

     * @return mixed

     * @throws BadRequestHttpException

     */

    public function actionResetPassword($token)

    {

        try {

            $model = new ResetPasswordForm($token);

        } catch (InvalidParamException $e) {

            throw new BadRequestHttpException($e->getMessage());

        }


        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {

            Yii::$app->session->setFlash('success', 'New password was saved.');


            return $this->goHome();

        }


        return $this->render('resetPassword', [

            'model' => $model,

        ]);

    }


}




// User model


<?php


namespace common\models;


use Yii;

use yii\web\IdentityInterface;

use yii\base\NotSupportedException;


/**

 * This is the model class for table "users".

 *

 * @property integer $id

 * @property string $name

 * @property string $username

 * @property string $password_hash

 * @property string $email

 * @property string $password

 * @property string $usertype

 * @property integer $block

 * @property integer $sendEmail

 * @property string $registerDate

 * @property string $lastvisitDate

 * @property string $activation

 * @property string $params

 * @property string $lastResetTime

 * @property integer $resetCount

 */

class User extends \yii\db\ActiveRecord implements IdentityInterface

{

    const SCENARIO_SIGNUP = 'reg';

    const SCENARIO_UPDATE = 'edit';


    public $auth_key;

    public $username;

    public $name;

    public $email;

    public $password;

    public $phone;

    public $rules;

    public $usertype;

    public $block;

    public $sendEmail;

    public $registerDate;

    public $lastvisitDate;

    public $activation;

    public $params;

    public $lastResetTime;

    public $resetCount;


    public function beforeSave($insert)

    {

        $return = parent::beforeSave($insert);

        $this->setPassword();

        return $return;

    }


    /**

     * @inheritdoc

     */

    public static function tableName()

    {

        return 'users';

    }


    /**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [['username', 'email'], 'filter', 'filter' => 'trim'],

            [['username'], 'unique', 'message' => 'Данное имя пользователя уже используется.'],

            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'email'],

            ['email', 'string', 'max' => 255],

            ['email', 'unique', 'message' => 'Выбранный E-Mail уже используется..'],

            [['username', 'email', 'phone'], 'required'],

            [['password'], 'required', 'on' => self::SCENARIO_SIGNUP],

            ['password', 'string', 'min' => 6],

            ['auth_key', 'string', 'max' => 255],

            [['rules'], 'required', 'on' => self::SCENARIO_SIGNUP],

            [['block', 'sendEmail', 'resetCount'], 'integer'],

            [['registerDate', 'lastvisitDate', 'lastResetTime'], 'safe'],

            [['params'], 'required', 'on' => self::SCENARIO_UPDATE],

            [['params'], 'string'],

            [['name'], 'string', 'max' => 255],

            [['username'], 'string', 'max' => 150],

            [['email', 'password', 'activation'], 'string', 'max' => 100],

            [['usertype'], 'string', 'max' => 25],

            ['phone', 'udokmeci\yii2PhoneValidator\PhoneValidator', 'format' => true, 'country' => 'ru'],

        ];

    }


    /**

     * @inheritdoc

     */

    public function attributeLabels()

    {

        return [

            'id' => 'ID',

            'name' => 'Имя входа',

            'username' => 'Имя пользователя',

            'email' => 'Email',

            'password' => 'Пароль',

            'usertype' => 'Тип пользователя',

            'block' => 'Блокирован',

            'sendEmail' => 'Отправлять уведомления',

            'registerDate' => 'Дата регистрации',

            'lastvisitDate' => 'Дата последнего визита',

            'activation' => 'Код активации',

            'params' => 'Параметры',

            'lastResetTime' => 'Дата последней смены пароля',

            'resetCount' => 'Количество сбросов пароля',

            'phone' => 'Телефон',

            'rules' => 'Согласен ',

        ];

    }


    public static function findIdentity($id)

    {

        return static::findOne($id);

    }


    public static function findIdentityByAccessToken($token, $type = null)

    {

        throw new NotSupportedException('You can only login by username/password pair for now.');

    }


    public function getId()

    {

        return $this->id;

    }


    public function getAuthKey()

    {

        return $this->auth_key;

    }


    public function validateAuthKey($authKey)

    {

        return $this->auth_key === $authKey;

    }


    public static function findByUsername($username)

    {

        return static::findOne(['username' => $username]);

    }


    public function validatePassword($password)

    {

        return Yii::$app->security->validatePassword($password, $this->password);

    }


    //get user by id

    public static function getById($user_id)

    {

        return static::find()->where(['id' => $user_id])->one();

    }


    public function setPassword()

    {

        $this->password = Yii::$app->security->generatePasswordHash($this->password);

    }


    /**

     * Generates "remember me" authentication key

     */

    public function generateAuthKey()

    {

        $this->auth_key = Yii::$app->security->generateRandomString();

    }


}




Here is a database structure:

CREATE TABLE users (

id INT(11) NOT NULL AUTO_INCREMENT,

name VARCHAR(255) NULL DEFAULT ‘’,

username VARCHAR(150) NULL DEFAULT ‘’,

email VARCHAR(100) NULL DEFAULT ‘’,

password VARCHAR(100) NULL DEFAULT ‘’,

usertype VARCHAR(25) NULL DEFAULT ‘’,

block TINYINT(4) NULL DEFAULT ‘0’,

sendEmail TINYINT(4) NULL DEFAULT ‘0’,

registerDate DATETIME NULL DEFAULT ‘0000-00-00 00:00:00’,

lastvisitDate DATETIME NULL DEFAULT ‘0000-00-00 00:00:00’,

activation VARCHAR(100) NULL DEFAULT ‘’,

params TEXT NULL,

lastResetTime DATETIME NULL DEFAULT ‘0000-00-00 00:00:00’ COMMENT ‘Date of last password reset’,

resetCount INT(11) NULL DEFAULT ‘0’ COMMENT ‘Count of password resets since lastResetTime’,

auth_key VARCHAR(255) NULL DEFAULT NULL

)

Besides all I’ve getting this exception after registration proceeded:





PHP Warning – yii\base\ErrorException


call_user_func() expects parameter 1 to be a valid callback, array must have exactly two members

1. in C:\xampp\path\to\local\vendor\yiisoft\yii2\base\Component.php at line 541

532533534535536537538539540541542543544545546547548549550                $event = new Event;

            }

            if ($event->sender === null) {

                $event->sender = $this;

            }

            $event->handled = false;

            $event->name = $name;

            foreach ($this->_events[$name] as $handler) {

                $event->data = $handler[1];

                call_user_func($handler[0], $event);

                // stop further handling if the event is handled

                if ($event->handled) {

                    return;

                }

            }

        }

        // invoke class-level attached handlers

        Event::trigger($this, $name, $event);

    }

2. yii\base\ErrorHandler::handleError(2, 'call_user_func() expects paramet...', 'C:\xampp\path\to\local...', 541, ...)

3. in C:\xampp\path\to\local\vendor\yiisoft\yii2\base\Component.php at line 541 – call_user_func(['frontend\models\Cart', 'afterLogin', 'frontend\models\Cart', 'afterLogin'], yii\web\UserEvent)

4. in C:\xampp\path\to\local\vendor\yiisoft\yii2\web\User.php at line 473 – yii\base\Component::trigger('afterLogin', yii\web\UserEvent)

5. in C:\xampp\path\to\local\vendor\yiisoft\yii2\web\User.php at line 245 – yii\web\User::afterLogin(common\models\User, false, 0)

6. in C:\xampp\path\to\local\frontend\controllers\SiteController.php at line 118 – yii\web\User::login(common\models\User)

112113114115116117118119120121122123124    {

        $model = new SignupForm();

 

        $user = $model->signup();

 

        if ($user && !$user->getErrors()) {

            if (Yii::$app->getUser()->login($user)) {

                return $this->goHome();

            }

        }

 

        return $this->render('signup', [

            'model' => new \common\models\User,

7. frontend\controllers\SiteController::actionSignup()

8. in C:\xampp\path\to\local\vendor\yiisoft\yii2\base\InlineAction.php at line 55 – call_user_func_array([frontend\controllers\SiteController, 'actionSignup'], [])

9. in C:\xampp\path\to\local\vendor\yiisoft\yii2\base\Controller.php at line 151 – yii\base\InlineAction::runWithParams([])

10. in C:\xampp\path\to\local\vendor\yiisoft\yii2\base\Module.php at line 455 – yii\base\Controller::runAction('signup', [])

11. in C:\xampp\path\to\local\vendor\yiisoft\yii2\web\Application.php at line 84 – yii\base\Module::runAction('site/signup', [])

12. in C:\xampp\path\to\local\vendor\yiisoft\yii2\base\Application.php at line 375 – yii\web\Application::handleRequest(yii\web\Request)

13. in C:\xampp\path\to\local\frontend\web\index.php at line 18 – yii\base\Application::run()

12131415161718    require(__DIR__ . '/../../common/config/main-local.php'),

    require(__DIR__ . '/../config/main.php'),

    require(__DIR__ . '/../config/main-local.php')

);

 

$application = new yii\web\Application($config);

$application->run();

 $_POST = [

    '_csrf' => 'bnVmY29xNlZcRhIGCxJQHVokPFAfM3c6GjctNQpAUBlbNFAFI0ZZBQ==',

    'User' => [

        'username' => 'test',

        'email' => 'test@test.test',

        'phone' => '+7 7777777777',

        'password' => '123123',

        'rules' => '1',

    ],

];