Меню

Yii2 ошибка сохранения модели

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 appmodulesuserscontrollers;
use Yii;
use yiiwebNotFoundHttpException;
use yiifiltersVerbFilter;
use yiiswiftmailerMailer;
use yiifiltersAccessControl;
use yiiwebResponse;
use yiiwidgetsActiveForm;
use appmodulesusersmodelsUsers;
use appcontrollersCommonController;

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

use Yii;
use yiibaseModel;
use yiidbActiveRecord;
use yiihelpersSecurity;
use yiiwebIdentityInterface;
use appmodulesusersmodelsUserType;

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.

Не могу понять почему не сохраняются данные в БД
При вызове метода save(false) у заполненной модели, создаются пустые поля в БД (хотя вроде как все правила для полей прописал):
Уж сижу несколько часов.

Контроллер (точнее один метод из него)

Код: Выделить всё

public function actionAddDriver(){

        $modelDriver = new Driver();

        $postRequest = Yii::$app->request->post();

        $isValidate = false;
        if($modelDriver->load($postRequest)){
            if($modelDriver->validate()){
                var_dump($modelDriver, true);
                $modelDriver->save(false);
                $isValidate = true;
            }
        }
        return $this->render('addDriver',['modelDriver'=>$modelDriver, 'isValidate'=>$isValidate]);
    }
 

Модель

Код: Выделить всё

<?php
namespace appmodels;

use yiidbActiveRecord;

class Driver extends ActiveRecord{

    public $name;
    public $lastname;
    public $patronymic;
    public $percent;

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

    public function getOrder(){
        return $this->hasMany(Order::className(),['driver_id'=>'id']);
    }

    public function attributeLabels(){
        return [
            'name'=>'Имя таксиста',
            'lastname'=>'Фамилия таксиста',
            'patronymic'=>'Отчество таксиста',
            'percent' => 'Процент'
        ];
    }

    public function rules(){
        return [
            [['name','percent'],'required'],
            [['name','lastname','patronymic'], 'string', 'length'=>[3,50]],
            ['percent','number'],
        ];
    }
}
 

Вид:

Код: Выделить всё

<?php
use yiiwidgetsActiveForm;
use yiihelpersHtml;
?>
    <?php if($isValidate):?>
        <div class="alert alert-success alert-dismissable">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            Запись добавлена!
        </div>
    <?php else:?>
        <div class="alert alert-warning alert-dismissable">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            ОШИБКА добавления!
        </div>
    <?php endif?>



<?php
$form = ActiveForm::begin(['id'=>'form-edit-driver','method'=>'post']);
    echo $form->field($modelDriver,'name')->textInput();
    echo $form->field($modelDriver,'lastname')->textInput();
    echo $form->field($modelDriver,'patronymic')->textInput();
    echo $form->field($modelDriver,'percent')->textInput();
    echo Html::submitButton('Добавить',['class'=>'btn btn-success']);
ActiveForm::end();

Даже не знаю с чем может быть проблема) знаю что из-за rules может не добавлять в БД, но вроде верно написал в правилах модели.

I encountered a tricky bug when did file uploading. The problem is that, when form validation is passed, $model->save() returns false, and $model->getErrors() returns an array with one error message regarding file input only.

And the scenario, where its used is the following:

There are 3 columns in a table (id, name, cover), and this is a very basic photo-album. The validation rules for this are pretty simple: when a user uploads a new photo, he must fill both name (input type="text") and cover (input type="file") fields. But when editing some existing record, he’s allowed not to upload a file, since that’s optional.

Pretty simple, right?

Now consider the relevant parts:

class Album extends ActiveRecord
{
    public $file;

    public function rules()
    {
        return [
            [['name'], 'required'],
            [['file'], 'file', 'extensions' => 'gif, jpg, jpeg, png', 'skipOnEmpty' => !$this->isNewRecord],
        ];
    }
}

After filling both name and file fields in the browser manually, Yii’s client-side validator highlights all fields green, which means that validation is passed successfully.

Here come the dragons now (after submitting successfully validated form):

public function actionCreate()
{
   $album = new Album();
   $album->load(Yii::$app->request->post());

   // The data is sent, $_POST and $_FILES aren't empty

   var_dump($album->save()); // false, but must be true
   print_r($album->errors); // Please upload a file (jeez, but a file is uploaded), but must be an empty array
}

This bug occurs only in «Add form», while it works in «Edit form». When I remove the file input everything works as expected, so that must be its own issue.

The environment itself, if that matters in this case:

  • PHP 5.6
  • Apache 2.2
  • Yii 2.0 (downloaded that version 2 months ago)
  • Tested on Windows/Linux, and all browsers

Рассмотрим на примере.

Код контроллера:

Код:

public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if (Yii::$app->request->post()) {
            $model->img = UploadedFile::getInstance($model, 'img');
            if($model->img){
                $model->upload();
            }
            if ( $model->save()) {
                Yii::$app->session->setFlash('success', "Соперник {$model->name} добавлен");

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

        return $this->render('update', [
            'model' => $model,
        ]);
    }

Код модуля:

Код:

public function upload()
    {
        if($this->validate()){
            $path = Yii::getAlias('@webroot') . '/upload/store/Rivals/' . $this->img->baseName . '.' . $this->img->extension;
            $this->img->saveAs($path);
            return true;
        }else{
            return false;
        }
    }

По идее все правильно, загружаем картинку и сохраняем модель. Но не тут то было. Сохранение модели не проходит валидацию, в последствии чего фаил загружается но вылетает ошибка.

finfo_file(/home/users/s/starnetkhv/tmp/phpEk1Rtb): failed to open stream: Нет такого файла или каталога

и в бд ничего не вносится

Происходит это из-за того что валидировать уже нечего.

Правильно будет сперва сохранить модель, а уже после загрузить файл.

I have made a drop down ajax for updating a model attribute in yii but it seems that model is not saving on the database and there is no validation error while Im checking the model

the view

<?php echo CHtml::dropDownList('roomType', $bed->room_type, SiteBed::roomTypes(), array('class' => 'room-types',
                'ajax' => array(
                    'type' => 'POST',
                    'url' => Yii::app()->createUrl("admission/admit/bedUpdate", 'ajax' => TRUE)),
                    'data' => array('Bed[room_type]' => 'js:this.value', 'bed_id' => $bed->bed_id),
                    'update' => '#Bed_room_type'
                )
            )); ?>

the controller

public function actionBedUpdate()
{
    if(!isset($_POST['bed_id']))
        throw new CHttpException(400, 'Bad Request');

    if(!isset($_POST['Bed']))
        throw new CHttpException(400, 'Bad Request');

    $model = Bed::model()->findByPk($_POST['bed_id']);

    if($model===null)
        throw new CHttpException(404,'The requested page does not exist.');

    $model->attributes = $_POST['Bed'];

    $model->save();

    //    throw new CHttpException(422, 'Saving Error');
}

model rules

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('name, status, price, room_type, house_id', 'required'),
        array('status, room_type, house_id', 'numerical', 'integerOnly'=>true),
        array('name', 'length', 'max'=>150),
        array('description', 'length', 'max'=>500),
        array('price', 'length', 'max'=>10),
        array('date_created, date_modified', 'length', 'max'=>14),
        // The following rule is used by search().
        // @todo Please remove those attributes that should not be searched.
        array('bed_id, name, description, status, price, room_type, house_id, date_created, date_modified', 'safe', 'on'=>'search'),
    );
}

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Yesterday i get up very early текст содержит разные ошибки
  • Y22dtr не заводится ошибок нет