Model-> save () Doesn't work in Yii2

Previously, I did not use the $model->save() function to insert or update any data. I just used createCommand() to execute the request, and it worked successfully. But my team members asked me to avoid createCommand() and use $model->save();

Now I started to clear my code, and the problem is $model->save(); not working for me. I do not know where I was wrong.

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('Ymd 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 is fine except $model->save(); Do not type 'asd' as I repeated it.

And if I write

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

It is not included in this if condition.

And if I write

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

Inserts NULL into all columns and prints 'asd'

.Php users (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('dmY h:i:s A', strtotime($CreatedAtDate)); return $CreatedAtDate; } public function getLastUpdatedDate() { $UpdatedDate = $this->updated_at; if ($UpdatedDate != 0) { $UpdatedDate = date('dmY 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 noticeable. Please help me.

+9
source share
11 answers

This may be a problem with your validation rules.

Try to save the model as a test without any verification as follows:

 $model->save(false); 

If the model is saved, you have a conflict with your validation rules. Try to selectively remove the validation rule to find a validation conflict.

If you override the value present in the active record, you do not assign the var value to db, but for this new var and then do not save.

Try to remove duplicated var. (Only characters not displayed in db should be declared here.)

+30
source

I think $model->load() returns false , calls $model->errors to see the model error.

 $model->load(); $model->validate(); var_dump($model->errors); 
+8
source

As shown in the @scaisEdge clause, try deleting all the fields associated with the table in the Users class

 class Users extends ActiveRecord implements IdentityInterface { /* removed because this properties is related in a table 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'; } /* ........... */ } 
+3
source

You make all the staff right. I think u should add one line to confirm password confirmation

 if(!$CheckExistingUser) { $auth_key = $model->getConfirmationLink(); $password = md5($post['password']); $registration_ip = Yii::$app->getRequest()->getUserIP(); $created_at = date('Ymd 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 the model attributes and error, for example:

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

Another solution mentioned is $model->save(false); , This is just a temporary workaround, and you still need to find the actual reason why the save function does not work.

Here are additional steps to help diagnose the actual problem:

  1. make sure _form input _form has the correct name, and
  2. check that if you added any dropdown menu function, check if it works correctly.
+1
source

Try the following:

 $model->save(false); 

and if that works, check your model rules () and your form rules () if they are with the same rules. usually the reason is the required fields in the table.

0
source

if your column type in your table is "integer" and your data is "string", you may see a tis error. You must check your data type and try again.

I suppose your column type is an integer, you should write the following code:

 $model->created_at=time();//1499722038 $model->save(); 

but your column type is a string, you should write the following code:

 $model->created_at=date('d/m/Y');//11/07/2017 $model->save(); 
0
source

And, perhaps, there is another reason not to save the model - you have a property of your Users class and before saving it from the form it is reset to NULL.

So, if you set $ model-> saveAttributes ('favorite_book' => $ model-> favorite_book), but at that time you declared public $ favourite_book in the Users class - you will get this field empty in the database.

0
source

Check the save model error as follows:

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

For those struggling with this problem, I remember to check the beforeSave method, if any. I mistakenly commented out the return expression.

 public function beforeSave($insert) { // never toggle comment on this!!! return parent::beforeSave( $insert); } 
0
source

in your model that I found. First name, last name, email address, password are required fields and you only update or save in your controller

  $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; 

but you must provide the first and last name and email id so that it throws a validation error to verify the use of this error

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

he will show you a mistake. correct the errors, then the model will get the save. you can solve this error using a script or

 $model->saveAttributes('favorite_book'=>$model->favorite_book,'favorite_movie'=>$model->favorite_movie); 

Hope this helps you.

-1
source

Source: https://habr.com/ru/post/1236167/


All Articles