Yii 2 Login From Db - Create User

Hi,

I am new to Yii and tested out your Basic template for user Yii2. I did manage to make the template login from a DB. The problem is after I successfully did this, the create/update user now fails.

I get this error:


Unknown Property – yii\base\UnknownPropertyException


Getting unknown property: app\models\User::email, username

Tracing this I get it from /Applications/MAMP/htdocs/yii/test-app/controllers/UserController.php – yii\db\BaseActiveRecord::save()

In this line:


if ($model->load(Yii::$app->request->post()) && $model->save()) {...}

It goes through $model->load but not $model->save().

Any ideas? Here are my codes for user controller and user model:

userController.php


<?php


namespace app\controllers;


use Yii;

use app\models\User;

use app\models\search\UserSearch;

use yii\web\Controller;

use yii\web\NotFoundHttpException;

use yii\filters\VerbFilter;


use yii\filters\AccessControl;


/**

 * UserController implements the CRUD actions for User model.

 */

class UserController extends Controller

{

    public function behaviors()

    {

        return [

            'verbs' => [

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

                'actions' => [

                    'delete' => ['post'],

                ],

            ],

            'access' => [

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

                'only' => ['create', 'update', 'delete'],

                'rules' => [

                    // deny all POST requests

                    [

                        'allow' => false,

                        'verbs' => ['post']

                    ],

                    // allow authenticated users

                    [

                        'allow' => true,

                        'roles' => ['@'],

                    ],

                    // everything else is denied

                ],

            ],

        ];

    }


    /**

     * Lists all User models.

     * @return mixed

     */

    public function actionIndex()

    {

        $searchModel = new UserSearch;

        $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());


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

            'dataProvider' => $dataProvider,

            'searchModel' => $searchModel,

        ]);

    }


    /**

     * Displays a single User model.

     * @param integer $id

     * @return mixed

     */

    public function actionView($id)

    {

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

            'model' => $this->findModel($id),

        ]);

    }


    /**

     * Creates a new User model.

     * If creation is successful, the browser will be redirected to the 'view' page.

     * @return mixed

     */

    public function actionCreate()

    {

        $model = new User;

        

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

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

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

                'model' => $model,

            ]);

        }

    }


    /**

     * Updates an existing User model.

     * If update is successful, the browser will be redirected to the 'view' page.

     * @param integer $id

     * @return mixed

     */

    public function actionUpdate($id)

    {

        $model = $this->findModel($id);


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

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

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

                'model' => $model,

            ]);

        }

    }


    /**

     * Deletes an existing User model.

     * If deletion is successful, the browser will be redirected to the 'index' page.

     * @param integer $id

     * @return mixed

     */

    public function actionDelete($id)

    {

        $this->findModel($id)->delete();


        return $this->redirect(['index']);

    }


    /**

     * Finds the User model based on its primary key value.

     * If the model is not found, a 404 HTTP exception will be thrown.

     * @param integer $id

     * @return User the loaded model

     * @throws NotFoundHttpException if the model cannot be found

     */

    protected function findModel($id)

    {

        if (($model = User::findOne($id)) !== null) {

            return $model;

        } else {

            throw new NotFoundHttpException('The requested page does not exist.');

        }

    }

}



user.php model


<?php


namespace app\models;


use Yii;


use yii\base\NotSupportedException;

use yii\db\ActiveRecord;

use yii\helpers\Security;

use yii\web\IdentityInterface;


use yii\behaviors\TimestampBehavior;

use yii\db\Expression;




/**

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

 *

 * @property integer $id

 * @property string $username

 * @property string $email

 * @property string $password

 * @property string $last_login_time

 * @property string $create_time

 * @property integer $create_user_id

 * @property string $update_time

 * @property integer $update_user_id

 *

 * @property MjcRegistryitem[] $mjcRegistryitems

 * @property MjcRegistrylist[] $mjcRegistrylists

 */

class User extends ActiveRecord implements IdentityInterface

{

  

    /**

     * @inheritdoc

     */

    public static function tableName()

    {

        return 'mjc_user';

    }


    /**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [['username', 'email', 'password'], 'required'],

//            [['last_login_time', 'create_time', 'update_time'], 'safe'],

            [['create_user_id', 'update_user_id'], 'integer'],

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

            [['email, username'], 'unique'],

            ['email', 'email'],

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

//            [['id', 'email', 'username', 'password', 'last_login_time', 'create_time', 'create_user_id', 'update_time', 'update_user_id'], 'safe', 'on' => 'search'],

        ];

    }


    /**

     * @inheritdoc

     */

    public function attributeLabels()

    {

        return [

            'id' => 'ID',

            'username' => 'Username',

            'email' => 'Email',

            'password' => 'Password',

            'last_login_time' => 'Last Login Time',

            'create_time' => 'Create Time',

            'create_user_id' => 'Create User ID',

            'update_time' => 'Update Time',

            'update_user_id' => 'Update User ID',

        ];

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getMjcRegistryitems()

    {

        return $this->hasMany(Cartitem::className(), ['create_user_id' => 'id']);

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getMjcRegistrylists()

    {

        return $this->hasMany(CartList::className(), ['create_user_id' => 'id']);

    }

    

    // Interface methods

    

    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/

    /**

     * @inheritdoc

     */

    public static function findIdentity($id)

    {

        return static::findOne($id);

    }


    /**

     * @inheritdoc

     */

    public static function findIdentityByAccessToken($token)

    {

        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');

    }


    /**

     * Finds user by username

     *

     * @param  string      $username

     * @return static|null

     */

    public static function findByUsername($username)

    {

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

    }


    /**

     * Finds user by password reset token

     *

     * @param  string      $token password reset token

     * @return static|null

     */

    public static function findByPasswordResetToken($token)

    {

        $expire = Yii::$app->params['user.passwordResetTokenExpire'];

        $parts = explode('_', $token);

        $timestamp = (int) end($parts);

        if ($timestamp + $expire < time()) {

            // token expired

            return null;

        }


        return static::findOne([

            'password_reset_token' => $token

        ]);

    }


    /**

     * @inheritdoc

     */

    public function getId()

    {

        return $this->getPrimaryKey();

    }


    /**

     * @inheritdoc

     */

    public function getAuthKey()

    {

        return $this->auth_key;

    }


    /**

     * @inheritdoc

     */

    public function validateAuthKey($authKey)

    {

        return $this->getAuthKey() === $authKey;

    }


    /**

     * Validates password

     *

     * @param  string  $password password to validate

     * @return boolean if password provided is valid for current user

     */

    public function validatePassword($password)

    {

        return $this->password === $password;//sha1($password);

//        return Security::validatePassword($password, $this->password_hash);

    }


    /**

     * Generates password hash from password and sets it to the model

     *

     * @param string $password

     */

    public function setPassword($password)

    {

        $this->password_hash = $password;//Security::generatePasswordHash($password);

    }


    /**

     * Generates "remember me" authentication key

     */

    public function generateAuthKey()

    {

        $this->auth_key = Security::generateRandomKey();

    }


    /**

     * Generates new password reset token

     */

    public function generatePasswordResetToken()

    {

        $this->password_reset_token = Security::generateRandomKey() . '_' . time();

    }


    /**

     * Removes password reset token

     */

    public function removePasswordResetToken()

    {

        $this->password_reset_token = null;

    }

    

    public function behaviors() 

    {

        return [

            'timestamp' => [

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

                'attributes' => [

                    ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],

                    ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time']

                ],

                'value' => new Expression('NOW()'),

            ],

        ]; 

    }

    

}



Thanks in advance!

  • yii newbie

Hi all,

I got it solved and it’s just one line causing the problem. I just commented it out then replaced it with separate rules:


//            [['email, username'], 'unique'],

            ['username', 'unique'],

            ['email', 'unique'],

;)

Change


[['email, username'], 'unique'],

to


[['email', 'username'], 'unique'],

If you are having issues with implementing login functionality from a database, here is really good post/video explaining everything:

http://code-epicenter.com/how-to-login-user-from-a-database-in-yii-framework-2/