Jump to content

Custom validation errors are getting displayed on form submit and not immediately


Recommended Posts

I have a form allowing the user to enter students' attendance. The scenario is that the user selects the Academic Year, ASC center, and Date. The user selects the students, then selects their corresponding standard, and selects the attendance status as shown in the image below. I have applied a custom validation to the Standard field, where the validation errors should be displayed immediately if the validation logic fails. Everything works correctly as expected, but the validation errors are displayed only after the form is submitted and not immediately. 

image.thumb.png.56a4a55efd9b2f58a44c71b7c4072d38.png

Below is the action create

public function actionCreate()
    {
        $model = new Attendancereport();
		$modelsStudentattendance = [new Attendancereportdetails];

		if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if ($model->load(Yii::$app->request->post())) {

			$identity = Yii::$app->user->identity->getonlyid();

			$model->UserId = $identity;

			$modelsStudentattendance = Model::createMultiple(Attendancereportdetails::classname());

            Model::loadMultiple($modelsStudentattendance, Yii::$app->request->post());

            $valid = $model->validate();
		    $valid = Model::validateMultiple($modelsStudentattendance) && $valid;


           if($valid)
			{
            		$transaction = \Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $model->save()) {

                        foreach ($modelsStudentattendance as $modelsStudentattendance) {
                            $modelsStudentattendance->AttendanceReportId = $model->AttendanceReportId;
                            if (! ($flag = $modelsStudentattendance->save())) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $transaction->commit();
                        return $this->redirect(['view', 'id' => $model->AttendanceReportId]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }

			}
        }

        return $this->render('create', [
                'model' => $model,
				'modelsStudentattendance' => (empty($modelsStudentattendance)) ? [new Attendancereportdetails] : $modelsStudentattendance,
            ]);
    }

Below is the form

 <?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\jui\DatePicker;
use wbraganca\dynamicform\DynamicFormWidget;
use app\models\Ascassignment;
use app\models\Asccenter;
use app\models\Academicyear;
use kartik\time\TimePicker;
use yii\helpers\ArrayHelper;
use app\models\Student;
?>
<script>

$(document).ready(function() {
$(".i").each(function(k,v){
$(".i").attr("disabled","true");
});
});

$(document).ready(function(){
	//When the user clicks on the plus button
 $(".dynamicform_studentattendance").on("afterInsert", function(e, item) {
	const $i = $(item).find('.i');
	
	//Populates all the student drop-down with the student names belonging to the ASC center
    $.post("index.php?r=student/student-lists&id="+$("select#attendancereport-ascid").val(),function(data){
    $i.html(data);
	});

	});

	$(".dynamicform_studentattendance").on("afterInsert", function(e, item) {
	//const $s = $(item).find('.s');

	var e = $(this);

	//Populates the Standard drop-down for selected student
    $.post("index.php?r=attendancereport/standard&aid="+$("select#attendancereport-academicyearid").val()+"&ascid="+$("select#attendancereport-ascid").val()+"&sid="+e.val(),function(data){
		e.closest("tr").find(".s").html(data);
					});
	});
});

</script>

<div class="attendancereport-form">

    <?php $form = ActiveForm::begin([
			'id' => 'dynamic-form', 
			'enableAjaxValidation' => true,
			'enableClientValidation' => true,
			'validateOnChange' => true,
			'validateOnBlur' => true,
			'options' => ['class' => 'disable-submit-buttons'],
   ]);?>
 <div class="panel panel-primary " >
<div class="panel panel-heading"><font size="3"><b>Student Attendance Report</b></font></div>
<div class="row">
<div class="col-sm-4">

   <?=	$form->field($model, 'AcademicYearId')->dropDownList(ArrayHelper::map(Academicyear::find()->where(['DisplayStatus'=>'Enabled'])->all(),'Id','academicyear'), ['prompt' => 'Select Academic Year','onChange'=>'

   				 var e = $(this);
			$.post("index.php?r=attendancereport/standard&aid=' . '"+$("select#attendancereport-academicyearid").val()+"&ascid=' . '"+$("select#attendancereport-ascid").val()+"&sid=' . '"+e.val(),function(data){

						e.closest("tr").find(".s").html(data);

                    });


	'])?>

	</div>

<div class="col-sm-4">

  <?= $form->field($model, 'ASCId')->dropDownList(ArrayHelper::map(Asccenter::find()->leftJoin('ascassignment','`ascassignment`.`ASCId`=`asccenter`.`ASCId`')->where(['ascassignment.UserId' => \Yii::$app->user->identity->getonlyid()])->all(),'ASCId','ASCName'), ['prompt' => 'Select ASC Center','class'=>'form-control ascid','onChange' => '

	$.post("index.php?r=student/student-lists&id=' . '"+$("select#attendancereport-ascid").val(),function(data){
					 $(".i").each(function(k,v)
					{
						$(".i").attr("disabled",false);
						 $(".i").html(data);

					}
					);

					});

				 var e = $(this);
			$.post("index.php?r=attendancereport/standard&aid=' . '"+$("select#attendancereport-academicyearid").val()+"&ascid=' . '"+$("select#attendancereport-ascid").val()+"&sid=' . '"+e.val(),function(data){

						$(".s option:not(:first-child)").remove();
						e.closest("tr").find(".s").html(data);

                    });

					'
]) ?>
</div>

<div class="col-sm-4">

   <?= $form->field($model, 'DateofReport')->widget(DatePicker::classname(), [
											//'language' => 'ru',
											'dateFormat' => 'yyyy-MM-dd',
											'options' => ['class' => 'form-control picker','readOnly'=>'readOnly'],
											'clientOptions'=>['changeMonth'=>false,
											'changeYear'=>false,
											'maxDate'=>'today',
											 'stepMonths'=> false,
											],

]) ?>
</div>
</div>
</div>
<div class="panel panel-primary">
		<div class="panel-heading"><font size="3"><b>Student Attendance Details</b></font></div>
<?php DynamicFormWidget::begin([
		'widgetContainer' => 'dynamicform_studentattendance',
		'widgetBody' => '.container-studentattendance',
		'widgetItem' => '.studentattendance-item',
		'limit' =>500,
		'min' => 1,
		'insertButton' => '.add-studentattendance',
		'deleteButton' => '.remove-studentattendance',
		'model' => $modelsStudentattendance[0],
		'formId' => 'dynamic-form',
		'formFields' => [
			'StudentId',
			'Standard',
			'AttendanceStatus',
		],
	]); ?>
	<table class="table table-bordered">
		<thead>
			<tr bgcolor='#B8B8B8'>
			<th style='border: 1px solid black;'></th>
			   <th class ="text-center" style='border: 1px solid black;'>Student</th>
				<th class ="text-center" style='border: 1px solid black;'>Standard</th>
				<th class ="text-center" style='border: 1px solid black;'>Attendance Status</th>
				<th class="text-center" style='border: 1px solid black;'>Action</th>
			</tr>
		</thead>
		<tbody class="container-studentattendance">
		<?php foreach ($modelsStudentattendance as $indexStudent => $modelStudentattendance): ?>
			<tr class="studentattendance-item">
				<td class="vcenter" style='border: 1px solid black;'>
					<?php
						// necessary for update action.
						if (! $modelStudentattendance->isNewRecord) {
							echo Html::activeHiddenInput($modelStudentattendance, "[{$indexStudent}]AttendanceReportDetailsId");
						}
					?>
					</td>
					<td style='border: 1px solid black;'>


				 <?= $form->field($modelStudentattendance, "[{$indexStudent}]StudentId")->label(false)->dropDownList(ArrayHelper::map(Student::find()->all(),'StudentId','StudentName'), ['prompt' => 'Select Student','class'=>'form-control i','onChange'=>'

				 var e = $(this);
			$.post("index.php?r=attendancereport/standard&aid=' . '"+$("select#attendancereport-academicyearid").val()+"&ascid=' . '"+$("select#attendancereport-ascid").val()+"&sid=' . '"+e.val(),function(data){

						e.closest("tr").find(".s").html(data);

                    });

	']) ?>
				</td>

				<td style='border: 1px solid black;'>

						<?= $form->field($modelStudentattendance, "[{$indexStudent}]Standard")->label(false)->dropDownList([], [
							    'prompt' => 'Select Standard',
							    'class' => 'form-control s',
						]) ?>

				</td>

				<td style='border: 1px solid black;'>


				 <?= $form->field($modelStudentattendance, "[{$indexStudent}]AttendanceStatus")->label(false)->dropDownList(['Present'=>'Present', 'Absent' => 'Absent'], ['prompt'=>'Select Attendance Status'])?>
				</td>

				<td class="text-center vcenter" style='border: 1px solid black;'>
				<button type="button" class="add-studentattendance btn btn-success btn-xs"><span class="fa fa-plus"></span></button>
					<button type="button" class="remove-studentattendance btn btn-danger btn-xs"><span class="fa fa-minus"></span></button>
				</td>
			</tr>
		 <?php endforeach; ?>
		</tbody>
	</table>
	<?php DynamicFormWidget::end(); ?>

</div>

    <div class="form-group">
       <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
		 <?= Html::resetButton('Reset',['class' => 'btn btn-default'])?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

 

 

Edited by PrashantS
Form code was missing

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.