Muhammad Shahzad
Muhammad Shahzad

Reputation: 9652

Yii2 before Validate throw PHP Warning

I used beforeValidate($insert) function and it thrown a PHP Warning when I access my post listing page: 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

but when I access my create page, this Exception gone away: http://localhost/yiiapp/backend/web/index.php?r=post/create

Actually I want to assign value one of my attribute user_id before validation in Post Model.

Here is 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;
    }
 ---
}

Why this Exception?

How I can solve this issue?

Upvotes: 3

Views: 8520

Answers (1)

SiZE
SiZE

Reputation: 2267

According to doc http://www.yiiframework.com/doc-2.0/yii-base-model.html#beforeValidate()-detail method beforeValidate has no attributes. Use it this way:

public function beforeValidate()
{
    if (parent::beforeValidate()) {
        return true;
    }
    return false;
}

Upvotes: 6

Related Questions