验证前的 Yii2 抛出 PHP 警告

Muh*_*zad 2 yii2 yii2-advanced-app

我使用了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
Run Code Online (Sandbox Code Playgroud)

但是当我访问我的创建页面时,这个异常消失了: http://localhost/yiiapp/backend/web/index.php?r=post/create

实际上,我想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;
    }
 ---
}
Run Code Online (Sandbox Code Playgroud)

为什么这个异常?

我该如何解决这个问题?

SiZ*_*iZE 5

根据文档http://www.yiiframework.com/doc-2.0/yii-base-model.html#beforeValidate()-detail方法 beforeValidate 没有属性。以这种方式使用它:

public function beforeValidate()
{
    if (parent::beforeValidate()) {
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)