Hamed Dehghan
Hamed Dehghan

Reputation: 65

how to validate a specific field in yii2

I need to do some stuff before saving my data in DB.

the problem is that the data changes during the validation and save process.

here is some code:

public function actionCreate()
{
    $model = new Customers();
    if ($model->load(Yii::$app->request->post()) && $model->validate('special_field')) {
        // do some stuff
        // data changes here 
        $model->save();
        return $this->redirect(['view', 'id' => $model->id]);
    }
    return $this->render('create', [
        'model' => $model,
    ]);
}

but $model->validate('special_field') function does not work

Upvotes: 1

Views: 559

Answers (1)

Hamed Dehghan
Hamed Dehghan

Reputation: 65

I've tried this and it worked properly


if ($model->load(Yii::$app->request->post())) {
    // your stuff
    if ($model->validate('special_field')) {
        $model->save();
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        $errors = $model->errors;
        var_dump($errors);
        die();
    }            
}

Upvotes: 1

Related Questions