我使用了beforeValidate($insert)
函数,当我访问我的帖子列表页面时它抛出了一个PHP警告:
http://localhost/yiiapp/backend/web/index.php?r=post/index
PHP Warning – yii\base\ErrorException
Missing argument 1 for app\models\Post::beforeValidate(), called in /var/www/html/yiiapp/vendor/yiisoft/yii2/base/Model.php on line 341 and defined
但是当我访问我的创建页面时,此异常消失了:
http://localhost/yiiapp/backend/web/index.php?r=post/create
实际上我想在Post Model中验证之前为我的属性user_id
赋值。
这是Post Model:
class Post extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'post';
}
public function beforeValidate($insert)
{
if (parent::beforeValidate($insert)) {
$this->user_id = Yii::$app->user->id;
return true;
}
return false;
}
---
}
为什么这个例外?
我如何解决这个问题?
答案 0 :(得分:3)
根据doc http://www.yiiframework.com/doc-2.0/yii-base-model.html#beforeValidate()-detail方法,beforeValidate没有属性。以这种方式使用它:
public function beforeValidate()
{
if (parent::beforeValidate()) {
return true;
}
return false;
}