Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax validation with custom id in yii2

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 ?

like image 781
krishn Patel Avatar asked Oct 29 '22 08:10

krishn Patel


1 Answers

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,
   ]);
like image 52
user206 Avatar answered Nov 11 '22 10:11

user206