如何在更新记录时阻止验证?我需要阻止它验证电子邮件,密码和密码确认。这是现行规则:
public function rules()
{
return [
[['first_name', 'last_name', 'email', 'password', 'password_confirm'], 'required'],
[['role_id', 'state_id', 'country_id', 'zip'], 'integer'],
[['first_name', 'last_name', 'email', 'password', 'address', 'city'], 'string', 'max' => 255],
[['password', 'password_confirm'], 'string', 'min' => 8],
['password_confirm', 'compare', 'compareAttribute' => 'password'],
['email', function($attribute) {
$user = static::findOne(['email' => Yii::$app->encrypter->encrypt($this->{$attribute})]);
if ($user) {
$this->addError($attribute, 'This email is already in use.');
}
}],
['email', 'email'],
];
}
答案 0 :(得分:2)
Sasha为什么要阻止更新验证?然而,这是不好的做法,如果你想让你的代码成为你的代码:
首先,您需要在模型中创建一个场景
namespace app\models;
use yii\db\ActiveRecord;
class {YourClass} extends ActiveRecord
{
/** Other stuff above */
public function scenarios(){
$scenarios = parent::scenarios();
$scenarios['update'] = ['!email', '!password', '!password_confirm'];
return $scenarios;
}
public function rules()
{
return [
[['first_name', 'last_name'], 'required'],
[['email', 'password', 'password_confirm'], 'safe', 'on'=>'update'],
[['role_id', 'state_id', 'country_id', 'zip'], 'integer'],
[['first_name', 'last_name', 'email', 'password', 'address', 'city'], 'string', 'max' => 255],
[['password', 'password_confirm'], 'string', 'min' => 8],
['password_confirm', 'compare', 'compareAttribute' => 'password'],
['email', function($attribute) {
$user = static::findOne(['email' => Yii::$app->encrypter->encrypt($this->{$attribute})]);
if ($user) {
$this->addError($attribute, 'This email is already in use.');
}
}],
['email', 'email'],
];
}
然后使用actionUpdate()
方法在setScenario('update)
中设置方案。
答案 1 :(得分:1)
要阻止验证特定操作的特定属性,您可以定义except
参数。
E.g:
public function rules()
{
return [
//some rules ...
['password_confirm', 'compare', 'compareAttribute' => 'password', 'except'=>['update']],
[['password', 'password_confirm'], 'required', 'except'=>['update']]
//some rules ...
];
}
然后在实例化新模型时的更新操作中,只需将方案设置为更新 $model->scenario = 'update'
答案 2 :(得分:0)
尝试使用核心事件:beforeValidate。你可以阅读它here