model->save() Not Working In Yii2

model example
model science definition
what is a model in research
model synonym
how to pronounce model
model male
models female
super model

Previously, I was not using $model->save() function for inserting or updating any data. I was simply using createCommand() to execute query and it was working successfully. But, my team members asked me to avoid createCommand() and use $model->save();

Now, I started cleaning my code and problem is $model->save(); not working for me. I don't know where i did mistake.

UsersController.php (Controller)

<?php
namespace app\modules\users\controllers;
use Yii;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;
use app\modules\users\models\Users;
use app\controllers\CommonController;

class UsersController extends CommonController 
{
    .
    .

    public function actionRegister() {
    $model = new Users();

        // For Ajax Email Exist Validation
   if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
     Yii::$app->response->format = Response::FORMAT_JSON;
     return ActiveForm::validate($model);
   } 

   else if ($model->load(Yii::$app->request->post())) {
      $post = Yii::$app->request->post('Users');
      $CheckExistingUser = $model->findOne(['email' => $post['email']]);

      // Ok. Email Doesn't Exist
      if(!$CheckExistingUser) {

        $auth_key = $model->getConfirmationLink();
        $password = md5($post['password']);
        $registration_ip = Yii::$app->getRequest()->getUserIP();
        $created_at = date('Y-m-d h:i:s');

        $model->auth_key = $auth_key;
        $model->password = $password;
        $model->registration_ip = $registration_ip;
        $model->created_at = $created_at;

        if($model->save()) {
          print_r("asd");
        }

      }

    } 
    }
    .
    .
}

Everything OK in this except $model->save(); Not printing 'asd' as i echoed it.

And, if i write

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

}

It's not entering to this if condition.

And, if i write

if($model->save(false)) {
    print_r("asd");
}

It insert NULL to all columns and print 'asd'

Users.php (model)

<?php

namespace app\modules\users\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
use app\modules\users\models\UserType;

class Users extends ActiveRecord implements IdentityInterface 
{

  public $id;
  public $first_name;
  public $last_name;
  public $email;
  public $password;
  public $rememberMe;
  public $confirm_password;
  public $user_type;
  public $company_name;
  public $status;
  public $auth_key;
  public $confirmed_at;
  public $registration_ip;
  public $verify_code;
  public $created_at;
  public $updated_at;
  public $_user = false;

  public static function tableName() {
    return 'users';
  }

  public function rules() {
    return [
      //First Name
      'FirstNameLength' => ['first_name', 'string', 'min' => 3, 'max' => 255],
      'FirstNameTrim' => ['first_name', 'filter', 'filter' => 'trim'],
      'FirstNameRequired' => ['first_name', 'required'],
      //Last Name
      'LastNameLength' => ['last_name', 'string', 'min' => 3, 'max' => 255],
      'LastNameTrim' => ['last_name', 'filter', 'filter' => 'trim'],
      'LastNameRequired' => ['last_name', 'required'],
      //Email ID
      'emailTrim' => ['email', 'filter', 'filter' => 'trim'],
      'emailRequired' => ['email', 'required'],
      'emailPattern' => ['email', 'email'],
      'emailUnique' => ['email', 'unique', 'message' => 'Email already exists!'],
      //Password
      'passwordRequired' => ['password', 'required'],
      'passwordLength' => ['password', 'string', 'min' => 6],
      //Confirm Password
      'ConfirmPasswordRequired' => ['confirm_password', 'required'],
      'ConfirmPasswordLength' => ['confirm_password', 'string', 'min' => 6],
      ['confirm_password', 'compare', 'compareAttribute' => 'password'],
      //Admin Type
      ['user_type', 'required'],
      //company_name
      ['company_name', 'required', 'when' => function($model) {
          return ($model->user_type == 2 ? true : false);
        }, 'whenClient' => "function (attribute, value) {
          return $('input[type=\"radio\"][name=\"Users[user_type]\"]:checked').val() == 2;
      }"], #'enableClientValidation' => false
      //Captcha
      ['verify_code', 'captcha'],

      [['auth_key','registration_ip','created_at'],'safe'] 
    ];
  }

  public function attributeLabels() {
    return [
      'id' => 'ID',
      'first_name' => 'First Name',
      'last_name' => 'Last Name',
      'email' => 'Email',
      'password' => 'Password',
      'user_type' => 'User Type',
      'company_name' => 'Company Name',
      'status' => 'Status',
      'auth_key' => 'Auth Key',
      'confirmed_at' => 'Confirmed At',
      'registration_ip' => 'Registration Ip',
      'confirm_id' => 'Confirm ID',
      'created_at' => 'Created At',
      'updated_at' => 'Updated At',
      'verify_code' => 'Verification Code',
    ];
  }

  //custom methods
  public static function findIdentity($id) {
    return static::findOne($id);
  }

  public static function instantiate($row) {
    return new static($row);
  }

  public static function findIdentityByAccessToken($token, $type = null) {
    throw new NotSupportedException('Method "' . __CLASS__ . '::' . __METHOD__ . '" is not implemented.');
  }

  public function getId() {
    return $this->id;
  }

  public function getAuthKey() {
    return $this->auth_key;
  }

  public function validateAuthKey($authKey) {
    return $this->auth_key === $auth_key;
  }

  public function validatePassword($password) {
    return $this->password === $password;
  }

  public function getFirstName() {
    return $this->first_name;
  }

  public function getLastName() {
    return $this->last_name;
  }

  public function getEmail() {
    return $this->email;
  }

  public function getCompanyName() {
    return $this->company_name;
  }

  public function getUserType() {
    return $this->user_type;
  }

  public function getStatus() {
    return $this->status;
  }

  public function getUserTypeValue() {
    $UserType = $this->user_type;
    $UserTypeValue = UserType::find()->select(['type'])->where(['id' => $UserType])->one();
    return $UserTypeValue['type'];
  }

  public function getCreatedAtDate() {
    $CreatedAtDate = $this->created_at;
    $CreatedAtDate = date('d-m-Y h:i:s A', strtotime($CreatedAtDate));
    return $CreatedAtDate;
  }

  public function getLastUpdatedDate() {
    $UpdatedDate = $this->updated_at;
    if ($UpdatedDate != 0) {
      $UpdatedDate = date('d-m-Y h:i:s A', strtotime($UpdatedDate));
      return $UpdatedDate;
    } else {
      return '';
    }
  }

  public function register() {
    if ($this->validate()) {
      return true;
    }
    return false;
  }

  public static function findByEmailAndPassword($email, $password) {
    $password = md5($password);
    $model = Yii::$app->db->createCommand("SELECT * FROM users WHERE email ='{$email}' AND password='{$password}' AND status=1");
    $users = $model->queryOne();
    if (!empty($users)) {
      return new Users($users);
    } else {
      return false;
    }
  }

  public static function getConfirmationLink() {
    $characters = 'abcedefghijklmnopqrstuvwxyzzyxwvutsrqponmlk';
    $confirmLinkID = '';
    for ($i = 0; $i < 10; $i++) {
      $confirmLinkID .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $confirmLinkID = md5($confirmLinkID);
  }

}

Any help is appreciable. Please Help me.

It could be a problem related with your validation rules.

Try, as a test, to save the model without any validation in this way:

$model->save(false);

If the model is saved you have conflict with your validation rules. Try selectively removing your validation rule(s) to find the validation conflict.

If you have redefined the value present in active record you don't assign the value to the var for db but for this new var and then are not save.

Try removing the duplicated var.. (only the vars non mapped to db should be declared here.)

Model, synonyms: replica, copy, representation, mock-up, dummy, imitation, double, duplicate, lookalike, reproduction, toy, miniature, facsimile, artificial, fake, make-believe, sham, false, spurious, bogus, counterfeit, pretend, phoney Large selection of ERTL die cast toys, banks, and collectibles.

I guess $model->load() returns false, call $model->errors to see model's error.

$model->load();
$model->validate();
var_dump($model->errors);

Model, a system or thing used as an example to follow or imitate. Choisissez le Modèle Wix® de Vos Rêves Puis Créez un Site Superbe Gratuitement ! Vaste Choix, Outil Design & Pro, Solution Mobile, Plan Référencement, Assistance Clientèle

As @scaisEdge suggest, try removing all table related field in your Users class

class Users extends ActiveRecord implements IdentityInterface 
{
  /* removed because this properties is related in a table's field 
  public $first_name;
  public $last_name;
  public $email;
  public $password;
  public $user_type;
  public $company_name;
  public $status;
  public $auth_key;
  public $confirmed_at;
  public $registration_ip;
  public $verify_code;
  public $created_at;
  public $updated_at;
  public $user_type;
  public $company_name;
  public $status;
  public $auth_key;
  public $confirmed_at;
  public $registration_ip;
  public $verify_code;
  public $created_at;
  public $updated_at;
  */

  // this is properties that not related to users table
  public $rememberMe;
  public $confirm_password;
  public $_user = false;

  public static function tableName() {
    return 'users';
  }

 /* ........... */

}

Model (person), "the law became a model for dozens of laws banning nondegradable plastic products" From your shopping list to your doorstep in as little as 2 hours. Save 5% w/ RedCard. Try Drive Up, Pick Up, or Same Day Delivery. We'll do the shopping for you.

Check model saving error like this :

if ($model->save()) {

} else {
  echo "MODEL NOT SAVED";
  print_r($model->getAttributes());
  print_r($model->getErrors());
  exit;
}

MODEL, synonyms: prototype, stereotype, archetype, type, version, style, mold, template, framework, pattern, design, guide, blueprint, paradigm, sample, example, exemplar, prototypical, prototypal, archetypal, illustrative Model definition is - a usually miniature representation of something; also : a pattern of something to be made. How to use model in a sentence. Synonym Discussion of model.

You are doing all staff correct. I think u must add one line for confirm password validation

if(!$CheckExistingUser) {    
$auth_key = $model->getConfirmationLink();
        $password = md5($post['password']);
        $registration_ip = Yii::$app->getRequest()->getUserIP();
        $created_at = date('Y-m-d h:i:s');

        $model->auth_key = $auth_key;
        $model->password = $password;
        $model->confirm_password= md5($post["confirm_password"]);  /// add  this line
        $model->registration_ip = $registration_ip;
        $model->created_at = $created_at;

And Also after this condition check model attributes and error like this :

if($model->save()) {
          print_r("asd");
        }else{
var_dump($model);exit;}

Models.com - The faces of fashion, a simplified description, especially a mathematical one, of a system or process, to assist calculations and predictions. Define model. model synonyms, model pronunciation, model translation, English dictionary definition of model. a standard or example for imitation; exemplary: a model

model, "a statistical model used for predicting the survival rates of endangered species" Model definition, a standard or example for imitation or comparison. See more.

model, fashion or shape (a three-dimensional figure or object) in a malleable material such as clay or wax. Model or modeling may refer to: . Model (art), a person who poses for a visual artist as part of the creative process. Model (conceptual), a representation of a system made of the composition of concepts

Model dictionary definition, use (a system, procedure, etc.) as an example to follow or imitate. 21 synonyms of model from the Merriam-Webster Thesaurus, plus 105 related words, definitions, and antonyms. Find another word for model.

Comments
  • Most likely a problem with your form. Check that Yii::$app->request->post() is populated correctly.
  • Hi Mr @chris--- , I did print_r(Yii::$app->request->post()); It echoed the value which I entered in form.
  • Ok weird. Check that the model is populated correctly right after the above line doing a var_dump($model->attributes); Also you messed up the parathesis in the line else if ($model->load(Yii::$app->request->post() && $model->validate())) above, where you say its not wentering the if condition. It should be else if ($model->load(Yii::$app->request->post()) && $model->validate())
  • var_dump($model->attributes); first line inside else if ($model->load(Yii::$app->request->post())) { } it echoing value @chris--- and, that $model->validate())) was typo. Sorry.
  • var_dump($model->attributes); just after $model = new Users(); it echoing NULL for all field @chris---
  • Hi Mr Scais. When i use $model->save(false);. NULL is getting inserted to table.
  • I Updated my question with Model Mr @Scais.
  • But you have redifined the value present in active record... I have update the answer... You are not using insert anymore.. you are using active record
  • You do not have to be sorry this is a mistake that I have made several times ... The important thing is that the answer is correct and that your programs to operate it properly
  • I have see you take the wrong road but i not insisted in my answer. (I know by my personal experience was right). I have hoped you return to my suggestion. The knowledge in our fields is a precoius stuff. Good Work and thanks..