Validation Yii2:条件验证不';我不打算重新提交
我启用了条件字段客户端验证-如果单选按钮的值为ContainerLudded等于1,则基本上需要containerPrice 验证规则Validation Yii2:条件验证不';我不打算重新提交,validation,yii2,Validation,Yii2,我启用了条件字段客户端验证-如果单选按钮的值为ContainerLudded等于1,则基本上需要containerPrice 验证规则 public function rules() { return [ [['monthlyTakeawayOrders', 'isContainerIncluded'], 'required'], ['containerPrice', 'required', 'when' => function($m
public function rules()
{
return [
[['monthlyTakeawayOrders', 'isContainerIncluded'], 'required'],
['containerPrice', 'required', 'when' => function($model){
return $model->isContainerIncluded;
}, 'whenClient' => "function(attribute, value) {
return $('#pricingform-iscontainerincluded input:checked').val() == 1;
}"
],
[['monthlyTakeawayOrders', 'containerPrice'],'integer']
];
}
表格
<?php $form = ActiveForm::begin(['id' => 'pricing-form']); ?>
<?= $form->field($pricingForm, 'monthlyTakeawayOrders') ?>
<?= $form->field($pricingForm, 'isContainerIncluded')->radioList([
0 => 'Option 0',
1 => 'Option 1'
]) ?>
<?= $form->field($pricingForm, 'containerPrice') ?>
<div class="form-group">
<?= Html::submitButton('Calculate', ['class' => 'btn btn-primary', 'name' => 'pricing-button']) ?>
</div>
<?php ActiveForm::end(); ?>
在大多数情况下,它可以正常工作,但当我提交IsContainerlcluded为0的表单时,然后将其切换到1并再次提交(不填写containerPrice),不会触发验证并提交表单,即使需要containerPrice
此外,在执行上述步骤后,如果我关注containerPrice字段,然后提交,则会显示错误消息,但表单仍会提交
表单是一种价格计算器,我通过ajax提交,因此提交后不会执行页面刷新,因为用户需要更改输入并再次提交表单以查看即时结果
我不知道为什么会发生这种情况,所以我们非常感谢您的帮助。谢谢 我试图重建此页面,但无法重现您的问题-您是否也可以提供接收表单的操作?您是否可以确认在切换时没有任何其他脚本绑定到该页面上的按钮,或者您是否在控制台中收到任何javascript错误。当你说表单已提交时,你的意思是服务器端验证也不会被调用,记录也会被保存吗?我已经在问题中添加了操作。当我切换时,控制台中没有错误,也没有绑定到操作的js。我们没有此表单的服务器端验证,因为它并不重要。我又玩了一点,似乎在我提到的场景中,没有执行验证,因为根本没有调用event beforeValidate。另一方面,afterValidate在某种奇怪的循环中被多次触发。正确触发提交之前的事件。我们使用它来处理ajax提交:
public function actionPartners()
{
$pricingForm = new PricingForm();
// pricing calculation processing
if ($pricingForm->load(Yii::$app->request->post())) {
$rates = $pricingForm->calculatePrice();
$shipping = $pricingForm->calculateShipping($rates['reducedRate']);
$table = $pricingForm->buildTable($rates['reducedRate']);
return \yii\helpers\Json::encode([
'rates' => $rates,
'shipping' => $shipping,
'deposit' => PricingForm::REBOX_DEPOSIT,
'table' => $table,
'isContainerIncluded' => $pricingForm->isContainerIncluded
]);
}
// get content
$products = ProductHelper::getProducts()->results;
$cmsApi = PrismicHelper::initiate();
$partnersHomepage = $cmsApi->getSingle('partners_homepage');
return $this->render('partners', [
'pricingForm' => $pricingForm,
'partnersHomepage' => $partnersHomepage,
'products' => $products,
]);
}