ankitr
ankitr

Reputation: 6172

Yii2 inline validation inside ActiveRecord Model

Here is the Model code with inline validation rule.

namespace app\models;

use Yii;

class Country extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'country';
    }

    public function rules()
    {
        return [
            ...other rules...
            ['pan_no', 'checkPanCardUsers', 'skipOnEmpty' => false, 'skipOnError' => false]
        ];
    }

    public function checkPanCardUsers($attribute, $params)
    {
        ...some condition ...
        $this->addError($attribute, 'custom error message');
    }
}

Controller code

public function actionSomeAction()
{
    $model = new Country();
    if ($model->load(Yii::$app->request->post()) {
        if($model->validate()) {
            $model->save();
        }
    }
    return $this->render('country', [
        'model' => $model,
    ]);
}

But the validation is not working.

Upvotes: 1

Views: 1142

Answers (1)

BHoft
BHoft

Reputation: 1663

Sure just use the following in your rules then your function will be called.

['pan_no', 'checkPanCardUsers', 'skipOnEmpty' => false, 'skipOnError' => false]

and just add your error in your function when your condition is wrong.

public function checkPanCardUsers($attribute, $params)
{
    //...some condition ...
    if (!$this->$attribute !='test')
        $this->addError($attribute, 'custom error message');
}

Hmm strange it works on my test flawlessly..

Check how you have created your model e.g. on create action:

$model = new ModelName();

Upvotes: 2

Related Questions