Помогите разобраться! Почему при подключении поведения не работает правило "compareAttribute"
Проблема такая, есть модель Users, добавление пользователей с паролями в таблицу, пароль должен вводиться дважды.
Сама по себе модель работает, пароль просит ввести дважды, сравнивает, в общем все четко.
В правилах добавил
Код: Выделить всё
[['password_confirm'], 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match" ],
Необходимо добавить логирование действий.
Создал поведение DBLog (весь код поведения ниже)
При подключении в других моделях
Код: Выделить всё
use common\modules\dblogs\models\DBLog;
.....
public function behaviors()
{
return [
DBLog::className(),
];
}
Код: Выделить всё
//[['password_confirm'], 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match" ],
Но все вместе выдает ошибку
Модель Users:Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: yii\validators\InlineValidator::compareAttribute
1. in /var/www/yii_test/vendor/yiisoft/yii2/base/Component.php at line 197
188189190191192193194195196197198199200201202203204205206 $behavior->$name = $value;
return;
}
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
}
/**
* Checks if a property is set, i.e. defined and not null.
* This method will check in the following order and act accordingly:
*
* - a property defined by a setter: return whether the property is set
* - a property of a behavior: return whether the property is set
Код: Выделить всё
<?php
namespace backend\modules\users\models;
use Yii;
use common\models\User;
use common\modules\dblogs\models\DBLog;
/**
* This is the model class for table "ts_user".
*
* @property integer $id
* @property string $username
* @property string $auth_key
* @property string $password_hash
* @property string $password_reset_token
* @property string $email
* @property integer $status
* @property integer $created_at
* @property integer $updated_at
*/
class Users extends \yii\db\ActiveRecord
{
public $action = 0; // -1 - update_pass, 0 - create, 1 - update,
public $password = '';
public $password_confirm = '';
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username'], 'required'],
[['password'], 'required', 'when' => function($model) {return $model->action < 1;}],
[['status', 'created_at', 'updated_at'], 'integer'],
[['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['username'], 'unique'],
[['email'], 'unique'],
[['password_reset_token'], 'unique'],
[['password_confirm'], 'required', 'when' => function($model) {return $model->action < 1;}],
[['password_confirm'], 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match" ],
];
}
public function behaviors()
{
return [
DBLog::className(),
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'username' => Yii::t('app', 'Username'),
'auth_key' => Yii::t('app', 'Auth Key'),
'password_hash' => Yii::t('app', 'Password Hash'),
'password_reset_token' => Yii::t('app', 'Password Reset Token'),
'email' => Yii::t('app', 'Email'),
'status' => Yii::t('app', 'Status'),
'created_at' => Yii::t('app', 'Created At'),
'updated_at' => Yii::t('app', 'Updated At'),
];
}
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
//$user->id = $this->id;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
}
public function update_pass()
{
if (!$this->validate()) {
return null;
}
//$user = new User();
$user = User::findOne($this->id);
//$user->isNewRecord = false;
$user->id = $this->id;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
}
}
Код: Выделить всё
<?php
namespace common\modules\dblogs\models;
use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use common\modules\dblogs\models\Logs;
use yii\web\HttpException;
use yii\web\User;
class DBLog extends Behavior
{
public function compare()
{
//echo 'compare!<hr>';
//exit;
// ...
}
public function addlog($act = null)
{
$log = new Logs();
if(Yii::$app->user->isGuest)
$log->user_id = null;
else
$log->user_id = (int)Yii::$app->user->identity->id;
$log->ip = (string)Yii::$app->request->userIP;
if(empty($log->ip)){
$log->ip = (string)Yii::t('app', 'Неудалось оптеделить IP адрес.');
}
$log->url = (string)Yii::$app->request->url;
if(empty($log->url)){
$log->url = (string)Yii::t('app', 'Неудалось оптеделить URL страницы.');
}
$log->user_host = (string)Yii::$app->request->userHost;
$log->user_agent = (string)Yii::$app->request->userAgent;
$log->act = (string)$act;
if(method_exists($this->owner, 'tableName')){
$log->model = (string)$this->owner->tableName();
}else{
if($act == 'LOGIN'){
$log->model = (string)'{{%user}}';
}else{
$log->model = (string)Yii::t('app', 'Неудалось оптеделить таблицу.');
}
}
if(!empty(get_class($this->owner))){
$log->model .= (string)' '.get_class($this->owner);
}else{
$log->model .= (string)' '.Yii::t('app', 'Неудалось оптеделить модель.');
}
$log->last_data = (string)serialize($this->owner->oldAttributes);
// if(property_exists($this->owner, 'oldAttributes') && count($this->owner->oldAttributes)){
// $log->last_data = (string)serialize($this->owner->oldAttributes);
// }else{
// //$log->last_data = (string)Yii::t('app', 'Нет данных.');
// $log->last_data = null;
// }
$log->new_data = (string)serialize($this->owner->attributes);
// if(property_exists($this->owner, 'attributes') && count($this->owner->attributes)){
// $log->new_data = (string)serialize($this->owner->attributes);
// }else{
// //$log->new_data = (string)Yii::t('app', 'Нет данных.');
// $log->new_data = null;
// }
$log->save();
if(count($log->errors)){
throw new HttpException(500 ,'Log error');
// echo '$log->errors:<pre>';
// print_r($log->errors);
// echo '</pre>';
}
}
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_INSERT => function(){$this->addlog('INSERT');},
ActiveRecord::EVENT_BEFORE_UPDATE => function(){$this->addlog('UPDATE');},
ActiveRecord::EVENT_BEFORE_DELETE => function(){$this->addlog('DELETE');},
];
}
}