I’m migrating my site from Yii to Yii2 and trying to make a basic loan calculator. was reading the documentation and some answers on stack that suggested to use validationUrl
.
Below is my code i’ve done so far. but i can’t get my form validation to work. It allows me to submit an empty form. and doesn’t show any errors?
Also where do i put my calculations, in actionloanValidate() or actionIndex() ?
<?php
$form = ActiveForm::begin([
'id' => $model->formName(),
'enableAjaxValidation' => true,
'validationUrl' => Url::toRoute(['calculator/default/loan-validate'])
]);
?>
<?= $form->field($model, 'price') ?>
<?= $form->field($model, 'downpayment') ?>
<?= $form->field($model, 'rate') ?>
<?= $form->field($model,'yearloan')->dropDownList(
['1' => '1 (12 months)', '2' => '2 (24 months)');
?>
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary btn-block', 'tabindex' => '3']) ?>
<?php ActiveForm::end(); ?>
<script>
$(document).ready(function () {
var $form = $("#<?= $model->formName() ?>");
$form.on("beforeSubmit", function (event, messages) {
event.preventDefault();
$.ajax({
"type":"POST",
"url":$form.attr('action'),
"data":$form.serialize(),
"beforeSend":function( xhr ) {},
"dataType":"json",
"cache": true,
"success":function(data){
$("#totalLoanAmount").html(data.totalLoanAmount);
$("#monthlyInstallment").html(data.monthlyInstallment);
$("#loanCalcTable").html(data.loanCalcTable);
},
});
return false;
});
});
</script>
in my controller i have this
public function actionIndex() {
$model=new calculatorForm;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
//DO CALCULATION HERE!!
}
return $this->render('loan-calculator', [
'model' => $model,
]);
}
public function actionloanValidate()
{
$model=new calculatorForm;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else {
return $this->renderAjax('loan-calculator', [
'model' => $model,
]);
}
}
my model rules are
public function rules() {
return [
//loan-calculator validation
[['price, downpayment, rate, yearloan'], 'required']
];
}