I need help in figuring out why my Ad Hoc Validation Error messages are not displayed in my Form.
If I hard code my validation rules in the model, Error messages correctly show in my form as you would expect. That works beautifully.
However, I have 65 models and each one has different validation rules stored in a php array. Instead of hard coding them manually in each model, I’m applying rules dynamically during validation.
For this example, I have an active form with one text input called "data" which must be a integer. This number must be between 900 and 3000. When I add rules in my controller validation method as described in the Guide (Ad Hoc Validation), the validation works and an Error Message is sent back to the form in the JSON Response. But the form does NOT highlight any labels and the error message is not displayed in the form. How do I get the errors to display in the form?
View file with Form
<?php $form = ActiveForm::begin([[
'id' => 'flat-form',
'action' => $saveUrl,
'enableAjaxValidation' => true,
'validationUrl' => Url::to(['/customers/validate-flat-data', 'mapID' => $model->mapID, 'arrayName' => $name]),
'options' => [
'class' => 'form-inline',
'method' => 'post',
],
]);
?>
<?= $form->field($model, 'data')
->textInput([
'maxlength' => true,
'class' => 'form-control help-block',
])
->label('Current Value')
?>
<?= Html::submitButton('Update',
[
'class' => 'btn btn-primary',
'id' => 'flat-submit-button',
]);
?>
<?php ActiveForm::end(); ?>
Controller with validation method:
public function actionValidateFlatData($mapID, $arrayName)
{
$customerID = CustomersSearch::getCustomerIDByMapID( $mapID );
$customerModel = $this->findModel($customerID);
$ecmFirmware = $customerModel->ecmFirmware;
$mapStructure = myFunctions::getMapStructure( $ecmFirmware );
$tableName = $mapStructure[$arrayName]['DBTableName'];
$min = $mapStructure[$arrayName]['min'];
$max = $mapStructure[$arrayName]['max'];
$request = Yii::$app->request;
if (Yii::$app->request->isAjax) {
$data = $request->post($tableName)['data'];
settype($data, "integer");
// ad hoc validation rule
$model = new DynamicModel( compact('data') );
$model->addRule(['data'], 'integer', ['min'=>$min, 'max'=>$max]);
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
Here are examples of the ajax response from the validation method:
{"dynamicmodel-data":["Data must be no less than 900."]}
{"dynamicmodel-data":["Data must be no greater than 3000."]}