Answer the question
In order to leave comments, you need to log in
How to validate fields depending on Yii2 check box selection?
The question is, how can you validate different fields depending on the selected checkbox
$model = Payment::find()->where(['user_id' => $id])->one();
$model->pre_auth_payment = "$28.25";
$model->scenario = "credit_card_form";
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if($model->pre_auth_payment == 0)
$model->scenario = "credit_card_form";
else
$model->scenario = "bank_account_form";
$model->save();
return $this->redirect(['update', 'id' => $model->user_id, 'step'=> 3]);
} else {
return $this->render('update', [
'model' => $model,
'step'=>$step
]);
}
[['user_id', 'payment_method', 'credit_card_number', 'credit_card_expr', 'credit_card_cvv', 'credit_card_info','type_pay'], 'required', 'when' => function($model) {
return $model->type_pay == 0;
}],
[[ 'pre_auth_payment', 'day_month', 'transit_number', 'institution_id', 'account_num'], 'required', 'when' => function($model) {
return $model->type_pay == 1;
}],
<code>
Answer the question
In order to leave comments, you need to log in
With the joint efforts in the Yii chat, such a solution was obtained.
public function rules()
{
return [
[['user_id', 'payment_method', 'credit_card_number', 'credit_card_expr', 'credit_card_cvv', 'credit_card_info','type_pay'], 'required', 'when' => function($model) {
return $model->type_pay == 0;
},'whenClient' => "function (attribute, value) {
return $('input[name=\"Payment[type_pay]\"]:checked').val() == 0;
}"],
[[ 'pre_auth_payment', 'day_month', 'transit_number', 'institution_id', 'account_num'], 'required', 'when' => function($model) {
return $model->type_pay == 1;
},'whenClient' => "function (attribute, value) {
return $('input[name=\"Payment[type_pay]\"]:checked').val() == 1;
}"],
[['user_id'], 'integer'],
[['type_pay'], 'required'],
[['payment_method', 'credit_card_number', 'credit_card_expr', 'credit_card_cvv', 'credit_card_info', 'pre_auth_payment', 'day_month', 'transit_number', 'institution_id', 'account_num'], 'string', 'max' => 255]
];
}
$model = Payment::find()->where(['user_id' => $id])->one();
$model->pre_auth_payment = "$28.25";
if ($model->load(Yii::$app->request->post()) {
$model->scenario = empty($model->type_pay) ? 'credit_card_form' : 'bank_account_form';
if ($model->validate()) {
// valid
}
}
You can make two separate models with the desired set of fields
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question