Answer the question
In order to leave comments, you need to log in
Yii2. How to validate dynamically added javascript fields?
I am adding a lot of new fields to the form with javascript. Field names look something like this
<input type="text" class="form-control" name="items[0][description]">
<input type="text" class="form-control" name="items[1][description]">
Answer the question
In order to leave comments, you need to log in
Open the source code of the page with the form you received, I assume that you already have the first field (which is potentially copied), then find the code with the js validation generated by yii, in order to validate the dynamic fields, after each addition of the field, you need to hang validation on it.
An example of my code, the validation code should be replaced with yours.
form.yiiActiveForm(
'add',
{
"id": 'eventoutcomes-' + index + '-comment',
"name": "[" + index + "]comment",
"container": '.field-eventoutcomes-' + index + '-comment',
"input": '#eventoutcomes-' + index + '-comment',
"validate": function (attribute, value, messages, deferred, $form) {
if ((function (attribute, value) {
if ($('#plannedoutcome-type').length > 0) {
return $('#plannedoutcome-event_type').val() != EVENT_TYPE_STAFF
&& $('#plannedoutcome-type').val() == TYPE_EVENT;
} else {
return $('#outcome-event_type').val() != EVENT_TYPE_STAFF
&& $('#outcome-type').val() == TYPE_EVENT;
}
})(attribute, value)) {
yii.validation.required(value, messages, {"message": "Обязательное поле"});
}
}
}
);
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'value')->input(
'number',
['pattern' => '\d*']
); ?>
...
<div class="event-outcomes-block">
<a class="btn btn-success add-event-outcome"><i class="fa fa-plus"></i> Добавить</a>
<div class='form-inline'>
<?php
if(is_array($aEventOutcomes) && count($aEventOutcomes) > 0) :
foreach ($aEventOutcomes as $index => $oEventOutcome) :
?>
<?= $form->field($oEventOutcome, "[$index]id")->input('hidden')->label(false); ?>
<div class="row">
<div class="col-lg-4 value">
<?= $form->field($oEventOutcome, "[$index]value")
->input('number', ['pattern' => '\d*']); ?>
</div>
<div class="col-lg-7 comment">
<?= $form->field($oEventOutcome, "[$index]comment")
->textInput(['prompt'=>'Комментарий']); ?>
</div>
<div class="col-lg-1 action-button">
<div class="form-group">
<a class="btn btn-xs btn-danger delete-button"><i class="fa fa-minus"></i></a>
</div>
</div>
</div>
<?php endforeach; endif; ?>
</div>
</div>
...
<div class="form-group">
<?= Html::submitButton(
'Подтвердить',
['class' => 'btn btn-info']
) ?>
</div>
<?php ActiveForm::end(); ?>
www.yiiframework.com/doc-2.0/yii-validators-eachva...
or write your own validator for this field
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question