0

  • Scenario

$scenarios['sell'] = [ 'deposit'];

  • Rule

['deposit', 'required', 'on' => 'sell',
            'message' => 'Deposit cannot be blank',
            'when' => function () {
                if (Yii::$app->controller->id == 'transaction' && $this->deposite_date != null) {
                    return true;
                }
            }
        ]

I want to validate the deposit field only in transaction controller and I pass any value in the deposit_date field. otherwise I don't want to validate the deposit field. but the validation happens in other controller as well.

Shamnad
  • 35
  • 5

1 Answers1

0

There is lot of code missing to understand how will be correct but I can try to make this.

First of all in controller action where you want to make this validation set some scenario. Example

public function actionTransaction()
{
    $model = new TransactionForm(); //model that have those needed rules
    $model->setScenario(TransactionForm::SCENARIO_SELL); //Set scenario for that model. SCENARIO_SELL const define as string like 'transaction' or 'sell' or whatever you like
    //Here goes load, validate and other piece of code that you need to process
}

Then in rules say that attribute is required on scenario that you created an no need for message because yii2 will generate for you (message you set if you need custom message text)

['deposit', 'required', 'on' => [self::SCENARIO_SELL],
        //If you need additional case for this rule based on another attribute then you add when
        'when' => function ($model) {
                /** @var self $model */ //Here define model where deposit_date is
            return $model->deposite_date != null; //This will return true or false and rule will works when it will return true.
        }
    ]

Hope that this helps.