Model not inserted due to validation error

Ребята, привет. такая проблема: делаю регистрацию, при вводе данных в форму все время вылазит ошибка "Введите пароль еще раз" (хотя в массиве POST есть пароль) и в базе данных такая запись:Model not inserted due to validation error. Двое суток уже не могу разобраться...подскажите! поля в table users id login password email question answer hash active acssess

Ребята, привет.
такая проблема: делаю регистрацию, при вводе данных в форму все время вылазит ошибка «Введите пароль еще раз» (хотя в массиве POST есть пароль) и в базе данных такая запись:Model not inserted due to validation error.
Двое суток уже не могу разобраться…подскажите!
поля в table users
id
login
password
email
question
answer
hash
active
acssess

вот код
модель

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

<?php
namespace appmodels;
use yiibaseModel;
use yiidbActiveRecord;
use yiidbExpression;

class RegisterForm extends ActiveRecord {

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

    public $password_repeat;
    public $check;

    public function attributeLabels() {
        return [
            'login' => 'Логин',
            'email' => 'Email',
            'password' => 'Введите пароль',
            'password_repeat' => 'Введите пароль еще раз',
            'question' => 'Секретный вопрос',
            'answer' => 'Ответ на вопрос',
            'check' => 'Я не робот',
        ];
    }

    public function rules() {
        return [
            [['login', 'email', 'password', 'password_repeat', 'question', 'answer', 'check',], required, 'message' =>'Заполните поле'],
            ['email', 'email'],
            [['password'],'string', 'length' => [6,30]],
            [['password_repeat'], 'compare', 'compareAttribute'=>'password', 'message'=>'Пароли не совпадают'],
            [['login','answer'], 'string','length' => [4,30]],
        ];
    }

     public function validation ($res) {
        if ($res != 1) {
                return false;
        }
    }
}
?>

контроллер

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

<?php

namespace appcontrollers;

use Yii;
use yiifiltersAccessControl;
use yiiwebController;
use yiifiltersVerbFilter;
use appmodelsLoginForm;
use appmodelsContactForm;
use appmodelsPages;
use appmodelsProducts;
use appmodelsProductsImage;
use appmodelsRegisterForm;

class SiteController extends AppController
{
 public function actionRegistration() {
 
        $model = new RegisterForm();
        $this->setMeta('IKA | Регистрация');
        $res = Yii::$app->request->post();
        if (!empty($res)) {
        $model->validation($res['RegisterForm']['check']);
        
          $passwd = $res['RegisterForm']['password'];
          $model->login = $res['RegisterForm']['login'];
          $model->password = $passwd;
          $model->email = $res['RegisterForm']['email'];
          $model->question = $res['RegisterForm']['question'];
          $model->answer = $res['RegisterForm']['answer'];
          $model->hash = md5($res['RegisterForm']['password']. $res['RegisterForm']['email']. $res['RegisterForm']['login']);
          $model->active = 0;
          $model->acssess = 1;
          echo $model->password_repeat;
          debug($res['RegisterForm']);
          if($model->save()) {
             Yii::$app->session->setFlash('success', 'Поздравляем! Вы успешно зарегистрировались.');
             return $this->refresh();
         } else {
             Yii::$app->session->setFlash('error', 'Ошибка регистрации!');
         }
        }
    return $this->render('registration', compact('model'));
    }
    }
 

вид

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

<?php

/* @var $this yiiwebView */
/* @var $form yiibootstrapActiveForm */
/* @var $model appmodelsLoginForm */

//use yiihelpersHtml;
//use yiibootstrapActiveForm;
use yiihelpersHtml;
use yiihelpersUrl;
use yiiwidgetsActiveForm;
?>
<div class="container">

<?php if (Yii::$app->session->hasFlash('success')) { ?>
        <div class="alert alert-success alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true"></span>&times</button>
            <?php echo Yii::$app->session->getFlash('success');?>
        </div>
    <?php } elseif (Yii::$app->session->hasFlash('error')) { ?>
    <div class="alert alert-danger alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true"></span>&times</button>
            <?php echo Yii::$app->session->getFlash('error');?>
        </div>
        <?php } ?>
   <?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'login')?>
<?= $form->field($model, 'email')->input('email') ?>
<?= $form->field($model, 'password')->passwordInput()?>
<?= $form->field($model, 'password_repeat')->passwordInput()?>
<?= $form->field($model, 'question')->dropDownList(['prompt' => 'Выберите вопрос', 'Любимое блюдо', 'Имя животного', 'Девичья фамилия матери', 'Любимый вид спорта', 'Марка автомобиля']);?>
<?= $form->field($model, 'answer')?>
<?= $form->field($model, 'check')->checkbox()?>
<?= Html::submitButton('Отправить', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
       
</div>

Да и скажите, можно ли в yii2 шифровать не md5 a crypt?

using yii ver 2.1.0
unable to attache the file
pasting it here

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yiidb;

use Yii;
use yiibaseInvalidConfigException;
use yiihelpersArrayHelper;
use yiihelpersInflector;
use yiihelpersStringHelper;

/*
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
class ActiveRecord extends BaseActiveRecord
{
    const OP_INSERT = 0x01;
    const OP_UPDATE = 0x02;
    const OP_DELETE = 0x04;
    const OP_ALL = 0x07;
    public function loadDefaultValues($skipIfSet = true)
    {
        foreach ($this->getTableSchema()->columns as $column) {
            if ($column->defaultValue !== null && (!$skipIfSet || $this->{$column->name} === null)) {
                $this->{$column->name} = $column->defaultValue;
            }
        }
        return $this;
    }

    public static function getDb()
    {
        return Yii::$app->getDb();
    }

    public static function findBySql($sql, $params = [])
    {
        $query = static::find();
        $query->sql = $sql;

        return $query->params($params);
    }

    protected static function findByCondition($condition)
    {
        $query = static::find();

        if (!ArrayHelper::isAssociative($condition)) {
            // query by primary key
            $primaryKey = static::primaryKey();
            if (isset($primaryKey[0])) {
                $pk = $primaryKey[0];
                if (!empty($query->join) || !empty($query->joinWith)) {
                    $pk = static::tableName() . '.' . $pk;
                }
                $condition = [$pk => $condition];
            } else {
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
            }
        }

        return $query->andWhere($condition);
    }

    public static function updateAll($attributes, $condition = '', $params = [])
    {
        $command = static::getDb()->createCommand();
        $command->update(static::tableName(), $attributes, $condition, $params);

        return $command->execute();
    }

    public static function updateAllCounters($counters, $condition = '', $params = [])
    {
        $n = 0;
        foreach ($counters as $name => $value) {
            $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
            $n++;
        }
        $command = static::getDb()->createCommand();
        $command->update(static::tableName(), $counters, $condition, $params);

        return $command->execute();
    }

    public static function deleteAll($condition = '', $params = [])
    {
        $command = static::getDb()->createCommand();
        $command->delete(static::tableName(), $condition, $params);

        return $command->execute();
    }


    public static function find()
    {
        return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
    }


    public static function tableName()
    {
        return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
    }


    public static function getTableSchema()
    {
        $schema = static::getDb()->getSchema()->getTableSchema(static::tableName());
        if ($schema !== null) {
            return $schema;
        } else {
            throw new InvalidConfigException("The table does not exist: " . static::tableName());
        }
    }


    public static function primaryKey()
    {
        return static::getTableSchema()->primaryKey;
    }


    public function attributes()
    {
        return array_keys(static::getTableSchema()->columns);
    }

    public function transactions()
    {
        return [];
    }

    /**
     * @inheritdoc
     */
    public static function populateRecord($record, $row)
    {
        $columns = static::getTableSchema()->columns;
        foreach ($row as $name => $value) {
            if (isset($columns[$name])) {
                $row[$name] = $columns[$name]->phpTypecast($value);
            }
        }
        parent::populateRecord($record, $row);
    }


    public function insert($runValidation = true, $attributes = null)
    {
        if ($runValidation && !$this->validate($attributes)) {
            Yii::info('Model not inserted due to validation error.', __METHOD__);
            return false;
        }

        if (!$this->isTransactional(self::OP_INSERT)) {
            return $this->insertInternal($attributes);
        }

        $transaction = static::getDb()->beginTransaction();
        try {
            $result = $this->insertInternal($attributes);
            if ($result === false) {
                $transaction->rollBack();
            } else {
                $transaction->commit();
            }
            return $result;
        } catch (Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    protected function insertInternal($attributes = null)
    {
        if (!$this->beforeSave(true)) {
            return false;
        }
        $values = $this->getDirtyAttributes($attributes);
        $fdaddy = $attributes[$attributes];
        error_log("HERE HERE : " .  __METHOD__ . "attributes = " . $attributes, 0 );
        if (empty($values)) {
            foreach ($this->getPrimaryKey(true) as $key => $value) {
                $values[$key] = $value;
            }
        }
        if (($primaryKeys = static::getDb()->schema->insert($this->tableName(), $values)) === false) {
            return false;
        }
        foreach ($primaryKeys as $name => $value) {
            $id = $this->getTableSchema()->columns[$name]->phpTypecast($value);
            $this->setAttribute($name, $id);
            $values[$name] = $id;
        }

        $changedAttributes = array_fill_keys(array_keys($values), null);
        $this->setOldAttributes($values);
        $this->afterSave(true, $changedAttributes);

        return true;
    }


    public function update($runValidation = true, $attributeNames = null)
    {
        if ($runValidation && !$this->validate($attributeNames)) {
            Yii::info('Model not updated due to validation error.', __METHOD__);
            return false;
        }

        if (!$this->isTransactional(self::OP_UPDATE)) {
            return $this->updateInternal($attributeNames);
        }

        $transaction = static::getDb()->beginTransaction();
        try {
            $result = $this->updateInternal($attributeNames);
            if ($result === false) {
                $transaction->rollBack();
            } else {
                $transaction->commit();
            }
            return $result;
        } catch (Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    public function delete()
    {
        if (!$this->isTransactional(self::OP_DELETE)) {
            return $this->deleteInternal();
        }

        $transaction = static::getDb()->beginTransaction();
        try {
            $result = $this->deleteInternal();
            if ($result === false) {
                $transaction->rollBack();
            } else {
                $transaction->commit();
            }
            return $result;
        } catch (Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }


    protected function deleteInternal()
    {
        if (!$this->beforeDelete()) {
            return false;
        }

        // we do not check the return value of deleteAll() because it's possible
        // the record is already deleted in the database and thus the method will return 0
        $condition = $this->getOldPrimaryKey(true);
        $lock = $this->optimisticLock();
        if ($lock !== null) {
            $condition[$lock] = $this->$lock;
        }
        $result = $this->deleteAll($condition);
        if ($lock !== null && !$result) {
            throw new StaleObjectException('The object being deleted is outdated.');
        }
        $this->setOldAttributes(null);
        $this->afterDelete();

        return $result;
    }

     public function equals($record)
    {
        if ($this->isNewRecord || $record->isNewRecord) {
            return false;
        }

        return $this->tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
    }

     public function isTransactional($operation)
    {
        $scenario = $this->getScenario();
        $transactions = $this->transactions();

        return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
    }
}

Организую загрузку картинок.

Модель:

class Image extends yiidbActiveRecord
{
    public $files;
     public function rules()
    {
        return [
            [[ 'id_actoutrs', 'id_category', 'id_pages', 'id_serial', 'id_user', 'for_home'], 'integer'],
            [['files'], 'file', 'extensions' => 'png, jpg'],
            [['title_alt', 'path', 'name'], 'string', 'max' => 255],
        ];
    }

Представление:

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
    <?= $form->field($model, 'title_alt')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'files[]')->fileInput(['multiple' => true]) ?>
    <?= $form->field($model, 'for_home')->radioList([
        '0' => Yii::t('app','NO'),
        '1' => Yii::t('app','YES')
    ]); ?>

Контролер:

public function actionCreate()
    {
        $model = new Image();
        $class=Yii::$app->request->get("class");
    $feilds =Yii::$app->request->get("feilds");
        $value=Yii::$app->request->get("value");
        if ($model->load(Yii::$app->request->post())) {
            $model->files = UploadedFile::getInstances($model, 'files');
            foreach ($model->files as $file) {
                $files_to = TransliteratorHelper::process($file->name, '', 'en');
                $years=date('Y');
                $mounts=date('m');
                $path =0;
                switch ($class) {
                    case 'category':
                        $path = 'category';
                        break;
                }
                if (file_exists(Yii::getAlias('@frontend/web/').$path.'/'.$years.'/'.$mounts.'/')) {
                } else {
                    mkdir(Yii::getAlias('@frontend/web/').$path.'/'.$years.'/'.$mounts.'/', 0775, true);
                }
                $file->saveAs(Yii::getAlias('@frontend/web/').$path.'/'.$years.'/'.$mounts.'/'.$files_to);
                $model->path=$path.'/'.$years.'/'.$mounts.'/';
                $model->name = $files_to;
                $model->save();
            } 

Дебаг показывает такую ошибку:

20:26:09.879 info yiidbActiveRecord::insert Model not inserted due to validation error.
C:OpenServerdomainsfilm.lcbackendcontrollersImageController.php (98)

print_r( $model->getErrors()) выдает такую ошибку:

Array ( [files] => Array ( [0] => Загрузите файл. ) ) 1

В чем проблема?

I have been fighting with an «invisible» error.
I am trying to do what I see as a simple update of a field, however the field never gets updated. Strangely, Yii2 doesn’t output any error except for the following log:

info yiidbActiveRecord::update Model not updated due to validation error.

Code in controler:

public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $scenario = (Yii::$app->user->identity->technology == $id) ? "updateOwner" : "updateGuest";

        $model->scenario = $scenario;
        $function = $scenario."Technology";

        if ($model->load(Yii::$app->request->post()) && $model->validate() && Technology::$function($model)) {
            return  $this->render(['view', 'model' => $model->id]);
        } else {
            return $this->render($scenario, [
                'model' => $model,
            ]);
        }
    }

The function in model:

public function updateGuestTechnology($model){
        $transaction = Yii::$app->db->beginTransaction();
         try 
            {   
                $technology = Technology::findOne($model->id);
                $user = Yii::$app->user->identity;

                $technology->scenario = "updateGuest";
                $technology->bno_coins += $model->bno_coins;
                $technology->bots += $model->bots;
                $technology->save();

                //The user query works just fine.
                $user->scenario = "update";
                $user->bots -= $model->bots;
                $user->bno_coins -= $model->bno_coins;
                $user->save();

                $transaction->commit();
            }
            catch (Exception $e)
            {
                $transaction->rollBack();
                Yii::error("Error during technology update by owner transaction. UserID: {$buyer->id}");
                return false; //Transaction failed
            }
            Yii::info("Technology updated by non-owner! Technology ID: {$technology->id} . UserID: {$user->id}");
            return true;
    }

Scenario:

"updateGuest" => ["bno_coins", "bots"],

Rules for bno_coins and bots:

//bno_coins rules
["bno_coins", "required", "on" => ["create", "updateOwner", "updateGuest"]],
["bno_coins", "integer", "min" => 0, "max" => Yii::$app->user->identity->bno_coins, "on" => ["create", "updateOwner", "updateGuest"]],

//bots rules
["bots", "required", "on" => ["create", "updateOwner", "updateGuest"]],
["bots", "integer", "min" => 0, "max" => Yii::$app->user->identity->bots, "on" => ["create", "updateOwner", "updateGuest"]],

$model->errors; Doesn’t contain any data. It seems that the whole $model doesn’t contain any values (that would explain why the validation fails). However, according to Yii Debugger, the requests contain all necessary information.

The project’s background changes and adding articles are suddenly invalid. Check the system log and find that

Module not inserted due to validation error.

In fact, the reason is very simple. The Baidu editor is added to the form, and name=»content» is used when naming the editor. Since the yii2 view page submits the form, the controller needs to use $model->load(). Check whether the current class name array exists.

Such as:

The submitted values ​​of the form elements in the view are placed in the Article[] array. Such an array will be generated when submitted

array (size=2)
  '_csrf' => string 'cUI2b280TUciBGctXXAHLUUmdwMaBSsRIzIAORd8HDQYNQ8YB38JLg==' (length=56)
  'Article' => 
    array (size=6)
      'title' => string 'This is a test article' (length=24)
      'add_time' => string '2015-10-15 08:39:43' (length=19)
      'author' => string 'qmsu' (length=4)
      'type_id' => string '1' (length=1)
      'status' => string '0' (length=1)
      'content' => string '<p>var_dump($post);</p>' (length=23)

If there are other values ​​outside of the array, $model->load() will return false, making it impossible to add or update data

eg: There is another data content outside the Article array, which makes it impossible to add or update data

array (size=2)
  '_csrf' => string 'cUI2b280TUciBGctXXAHLUUmdwMaBSsRIzIAORd8HDQYNQ8YB38JLg==' (length=56)
  'Article' => 
    array (size=6)
      'title' => string  'This is a test article' (length=24)
      'add_time' => string '2015-10-15 08:39:43' (length=19)
      'author' => string 'qmsu' (length=4)
      'type_id' => string '1' (length=1)
      'status' => string '0' (length=1)
  'content' => string '<p>var_dump($post);</p>' (length=23)

Therefore, when naming form elements on the view page, you should use the following method name=»Article[content]»

<input type="text" maxlength="255" value="" name="Article[content]" class="form-control" id="article-author">

Note: If you use yii2 to automatically generate the form, you don’t need to worry about this issue

Аее! Доделал кучу плюшек для бота)

Кто хочет занятся мордой?)

@236286 Хз просто на ютубе нашёл

@lavrentiev я вообще понял, что это не yii

@arogachev нашёл тебя в Твитере самым первым Твитер тебя показал )

что вы думаете о vivaldi?

@hellvesper оперу напоминает )

@lavrentiev да? в смысле, чем?

помню раньше опера была яркая

дизайн кстати чуть менее чем полностью слизан с Edge

под 10кой поэтому эргономично смотриться =) а вот под другими осями немного диковато)

@lavrentiev а че ярким? потому что красный?

«Model not inserted due to validation error.» — это что такое?

«Model not inserted due to validation error

@236286 var_dump(model->errors);

да, вызови после model->validate

там где у тебя model->validate либо model->save вызывается

@hellvesper if ($model->load(Yii::$app->request->post()) && $model->save()) тут ошибка?

ошибка у тебя во входящих данных, выведи model->errors вардампом чтобы посмотреть где и что именно

var_dump(model->errors); ]

@hellvesper кстати тут я просто помогаю парню с зарубежного чата yii2

Bad Request (#400)
Не удалось проверить переданные данные. — уменя когда большие файлы грузятся

скорее всего проблема в csrf

@hellvesper блин а щас вообще никакие не грузит файлы

скорее всего в этом и была проблема изначально)

ошибки смотреть что как происходит

в дебаггере смотреть какие данные приходят

занчит смотреть в дебаггере

MyForm [
‘name’ => [
‘file’ => ‘julianna-karaulova-ty-ne-takojj-(best-muzon.com).mp3’
]
‘type’ => [
‘file’ => »
]
‘tmp_name’ => [
‘file’ => »
]
‘error’ => [
‘file’ => 1
]
‘size’ => [
‘file’ => 0
]
]

все норм вроде файл приходит

[[‘file’], ‘file’, ‘extensions’ => ‘mp3’]

убери валидатор вообще и попробуй сохранить

просто [[‘file’], ‘file’]

@hellvesper а че за валдидатор

public function rules() {
return [
// name, email, subject and body are required
[[‘name’, ’email’], ‘required’, ‘message’ => ‘Не заполненно полища’],
// email has to be a valid email address
[’email’, ’email’, ‘message’ => ‘Некоректный email адрес!’], // введи не верный мелй и будет твоя ошибка
[[‘file’], ‘file’, ‘extensions’ => ‘mp3’]
];
}

так где ты задаешь mp3 это валидатор

удали этот кусок и попробуй

@hellvesper Блин ниче не работает

@hellvesper $form->file = UploadedFile::getInstance($form, ‘file’);

        $form->file->saveAs('photo/'.$form->file->baseName.".".$form->file->extension);

<?php $f = ActiveForm::begin([‘options’ => [‘enctype’ => ‘multipart/form-data’]]); ?>

<?=$f->field($form, ‘file’)->fileInput()?>
<?=Html::submitButton(‘Отправить’); ?>

<?php $f = ActiveForm::end(); ?>

@hellvesper просто тупо картинки грузятся без валидации

@hellvesper один 10 другой 3

хотя можешь проверить какой размер поста стоит

там же в дебаггере вкладка configuratons

посмотри upload_max_file_size и max_post_size

Снимок экрана 2015-11-01 в 18.35.35.png

upload_max_filesize 2M 2M

ну вот поэтому и не грузится мп3

попробуй на 1 метр загрузить

@hellvesper блин забыл опять где это менять

Снимок экрана 2015-11-01 в 18.37.39.png

@hellvesper ура щас грузит

еще вот, что сильно высоконагруженный музыкальный портал на чем лучше делать?
на php или java?
руби ли python?

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

Все едино. Решает не язык а руки.

Понравилась статья? Поделить с друзьями:
  • Mode exception not handled windows 10 как исправить
  • Mode 255 flash status error
  • Modbus ошибки протокола
  • Modbus ошибка устройства 129
  • Modbus tcp error codes