Yii2在验证之前计算字段数据
问题描述:
我的模型包含字段“authorname”,它在创建记录时必须由表单验证之前的当前用户登录替换。Yii2在验证之前计算字段数据
好吧,我在适当的控制器中写道:
public function beforeValidate() {
if($this->isNewRecord) {
$this->authorname = Yii::$app->user->identity->username;
}
return parent::beforeValidate();
}
它的工作原理 - 不需要显示形式计算领域,substituion做工不错。
除了一个令人不快的东西 - 数据网格上方的搜索字符串也有$ this-> isNewRecord = true并通过用户名筛选整个数据数组。 如何执行Yii2不会将搜索记录评估为新记录? 或者如何编写beforeValidate()函数来获取真正插入的数据和虚拟插入的搜索行之间的区别?
答
从SearchModel删除行:
andFilterWhere(['like', 'authorname', $this-> authorname])
或
'authorname' => $this->authorname,
+0
不是100%,但在我的情况下足够了 –
你为什么不为'authorname'默认值设置为规则的当前用户名?比'beforeValidate()'简单。我不知道你的用例,但我猜想更简单。 –
您应该使用beforeSave而不是beforeValidate。 – nicolascolman
@nicolascolman这是错误的 - 空字段块保存前验证。因此,在saveSave之前重写 - 太晚了。 –