6

I have a same field in foreach loop like below

foreach ( $subCategoryData as $k => $val) {
    <?= $form->field($model, 'sub_category', ['template' => '{input}'])->textInput(['maxlength' => 255, 'class' => 'form-control required section_name', 'name' => "Category[sub_category][$k][name]"]) ?>
} ?>

I have ajax validation with custom method it is working fine.

But it is Working with only first input. Because it has same ID.

But when I changed it with 'inputOptions' => ['id' => 'myCustomId'] and make it unique with below and my ajax validation is not called.

foreach ( $subCategoryData as $k => $val) {
    <?= $form->field($model, 'sub_category', ['template' => '{input}','inputOptions' => ['id' => "category-sub_category_".$k]])->textInput(['maxlength' => 255, 'class' => 'form-control required section_name', 'name' => "Category[sub_category][$k][name]"]) ?>
}

I have seen this solution here https://github.com/yiisoft/yii2/issues/7627

and also seen this https://stackoverflow.com/a/28460442/2286537

But nothing work can anyone help me ?

Community
  • 1
  • 1
krishn Patel
  • 2,579
  • 1
  • 19
  • 30
  • I see in this link a possible answer: http://stackoverflow.com/questions/30738180/yii2-validation-rule-for-multiple-inputs-with-same-name – Alejandro Apr 21 '17 at 20:58

1 Answers1

2

Your question is different from the posts you introduced. You should use loadMultiple.

Example:

if (\Yii::$app->request->isAjax) {
    if (\yii\base\Model::loadMultiple($model,\Yii::$app->request->post())) {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        echo json_encode(ActiveForm::validateMultiple($model));
        \Yii::$app->end();
    }
}

if ( \yii\base\Model::loadMultiple($model, Yii::$app->request->post()) &&  \yii\base\Model::validateMultiple($model)) {
      foreach ($model as $models) {
          $models->save(false);
      }

in view:

<?php $form = ActiveForm::begin([
      'enableAjaxValidation' => true,
   ]);
user206
  • 1,085
  • 1
  • 10
  • 15