We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How to populate nested form inputs with the data from server

In general how to populate all the nested inputs of the form with the data returned from server using jQuery. I have assigned a class attribute to the StudentId field in the nested form and used each function of the jquery to populate all the data into the form fields in nested form. But the data gets populated only on the first row. As I click on the button to add new students then the previously populated data gets cleared and so the user has to select the value from the drop down again and again for the data to get populatedc. Below is the code for main form.

$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=' . '"+$(this).val(),function(data){ $(".i").each(function() { $(".i").html(data); // Populate the StudentId field having the class .i with the data }); }); '

]) ?>

Below is the code for nested form field

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



4 Replies

SP Sureshkumar P Syncfusion Team March 21, 2023 10:23 AM UTC

Hi Prashant,

Due to insufficient details, we cannot proceed with this request further, please explain your requirement in detailed information with any image or video demonstration. Also, please share the dropdownlist component rendering code example with the form adding field button click method handler. This detail will help us to provide an exact solution as earlier as possible.

Regards,

Sureshkumar P



PS Prashant Sontale March 21, 2023 02:28 PM UTC

I have attached 2 images.The first image shows the form where user selects the ASC center from the drop down list.Upon selection of ASC center the the function returns all the students belonging for that ASC center.Now these students should be populated for every Students field in the nested form.The students gets populated for the first row as shown in the first image.

Now when the user clicks on Add Student button to add more students then the previously populated student data gets cleared from the Student field. This is shown in the second image

First Image

image.png


Second Image

image1.png


Below is the function which returns the students for selected ASC


public function actionStudentLists($id)
    {
        $countstudents = Student::find()->where(['ASCId' => $id])->count();//Counts number of students

        $Students = Student::find()->where(['ASCId' => $id])->all(); // Execute students for ASCId

        if ($countstudents > 0) {

        echo "";  

            foreach ($Students as $Student) {
        ob_start();

             echo " . $Student->StudentName . "";
            }
        } else {
            echo "";
        }
    }

 Below is the _form.php


<?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 kartik\time\TimePicker;
use yii\helpers\ArrayHelper;
use app\models\Student;
?>

<script>

$(function () {
$(".dynamicform_student").on("beforeInsert", function(e, item) {
   $.post("index.php?r=student/student-lists&id='.'"+$("select#ascteacherreport- 
                ascid").val(),function(data){
                         $(".i").html(data); 
                   });
              });
          });

$(function () {
$(".dynamicform_wrapper").on("beforeInsert", function(e, item) {
            $.post("index.php?r=student/student-lists&id=' . '"+$("select#ascteacherreport-
                  ascid").val(),function(data){  
                 $(".i").html(data);
            });
        });
     });
</script>

<div class="ascteacherreport-form">

<?php $form = ActiveForm::begin(['id' => 'dynamic-form',  'options' => ['class' => 'disable-submit-
  buttons'], ]);?>

<div class="panel panel-primary " >
 <div class="panel panel-heading"><font size="3"><b>Teacher Report</b></font></div>
  <div class="row">
   <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=' . '"+$(this).val(),function(data){
                $(".i").each(function()
                {
                 $(".i").html(data); // Populate the StudentId field having the class .i with the 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'=>true,
                       'changeYear'=>true,
                       'readOnly'=>true
                      ]]) ?>
</div>
</div>
</div>

<div class="panel panel-primary">
<div class="panel-heading"><font size="3"><b>Time and Student Details</b></font></div>
    <?php DynamicFormWidget::begin([
        'widgetContainer' => 'dynamicform_wrapper',
        'widgetBody' => '.container-items',
        'widgetItem' => '.time-item',
        'limit' =>10,
        'min' => 1,
        'insertButton' => '.add-time',
        'deleteButton' => '.remove-time',
        'model' => $modelsTime[0],
        'formId' => 'dynamic-form',
        'formFields' => [
        'FromTime',
        'ToTime'
        ],
    ]); ?>
<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;'>Time</th>
                <th class ="text-center" style='border: 1px solid black;'>Student Details</th>
                    <th class="text-center" style='border: 1px solid black;'>
                            <button type="button" class="add-time btn btn-success btn-xs"><span 
                              class="fa fa-plus"></span> Add Time</button>
                    </th>
                </tr>
  </thead>
  <tbody class="container-items">
      <?php foreach ($modelsTime as $indexTime => $modelTime): ?>
        <tr class="time-item">
          <td class="vcenter" style='border: 1px solid black;'>
                <?php
                // necessary for update action.
                if (! $modelTime->isNewRecord) {
                        echo Html::activeHiddenInput($modelTime, "[{$indexTime}]ASCReportDetailsId");
                }
                ?>
         </td>
         <td style='border: 1px solid black;width:15%'>
                 <?=  $form->field($modelTime, "[{$indexTime}]FromTime")->label(true)-
                             >widget(TimePicker::classname(),[
                               'pluginOptions' => [
                                    'readOnly' => true,
                                    'minuteStep' => 1,
                         ],
                    ])?><br>

                <?=$form->field($modelTime, "[{$indexTime}]ToTime")->label(true)-
                               >widget(TimePicker::classname(),[
                                'pluginOptions' => [
                                    'readOnly' => true,
                                    'minuteStep' => 1,
                        ],
                    ])?>
        </td>
        <td style='border: 1px solid black;'>
                <?= $this->render('_form-studentdata', [
                                     'form' => $form,
                                    'indexTime' => $indexTime,
                                    'modelsStudentdata' => $modelsStudentdata[$indexTime],
                               ]) ?>
        </td>
        <td class="text-center vcenter" style='border: 1px solid black;'>
            <button type="button" class="remove-time 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']) ?>
    </div>
<?php ActiveForm::end(); ?>

</div>



 Below is the nested inner form _form-studentdata.php



<?php

use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\bootstrap\ActiveForm;
use yii\web\UploadedFile;
use wbraganca\dynamicform\DynamicFormWidget;
use app\models\Student;
?>

<?php DynamicFormWidget::begin([
    'widgetContainer' => 'dynamicform_student',
    'widgetBody' => '.container-student',
    'widgetItem' => '.student-item',
    'limit' => 50,
    'min' => 1,
    'insertButton' => '.add-student',
    'deleteButton' => '.remove-student',
    'model' => $modelsStudentdata[0],
    'formId' => 'dynamic-form',
    'formFields' => [
        'StudentId',
        'Subject',
        'Topic',
        'Confidence',
    ],
]); ?>
<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;'>Subject</th>
               <th class ="text-center" style='border: 1px solid black;'>Topic</th>
            <th class ="text-center" style='border: 1px solid black;'>Confidence</th>
            <th class="text-center" style='border: 1px solid black;'>
                <button type="button" class="add-student btn btn-success btn-xs"><span
                      class="glyphicon glyphicon-plus"></span> Add Student</button>
            </th>
        </tr>
    </thead>
    <tbody class="container-student">
    <?php foreach ($modelsStudentdata as $indexStudent => $modelStudentdata): ?>
        <tr class="student-item">
            <td class="vcenter" style='border: 1px solid black;'>
                <?php
                    // necessary for update action.
                    if (! $modelStudentdata->isNewRecord) {
                        echo Html::activeHiddenInput($modelStudentdata, "[{$indexTime}]
                                 [{$indexStudent}]ASCTeacherReportTimeDetailsId");
                    }
                ?>
    </td>
        <td style='border: 1px solid black; width:30%'>
                
             <?= $form->field($modelStudentdata, "[{$indexTime}][{$indexStudent}]StudentId")-
                 >label(false)->dropDownList(ArrayHelper::map(Student::find()-
                 >all(),'StudentId','StudentName'),['prompt' => 'Select 
                 Student','class'=>'form-control i']) ?   // class i assigned to StudentId field

       </td>
        <td style='border: 1px solid black; width:30%'>

            <?= $form->field($modelStudentdata, "[{$indexTime}][{$indexStudent}]Subject")-
                   >label(false)->textInput(['maxlength' => true]) ?>

       </td>
    <td style='border: 1px solid black; width:30%'>
        <?= $form->field($modelStudentdata, "[{$indexTime}][{$indexStudent}]Topic")->label(false)-
                               >textInput(['maxlength' => true]) ?>
    </td>

    <td style='border: 1px solid black; width:30%'>
                <?= $form->field($modelStudentdata, "[{$indexTime}][{$indexStudent}]Confidence")-
                                >label(false)->textInput(['maxlength' => true]) ?>
    </td>
     <td class="text-center vcenter" style=" border: 1px solid black;width: 90px;">
        <button type="button" class="remove-student btn btn-danger btn-xs"><span class="glyphicon 
              glyphicon-minus"></span>
        </button>
    </td>
  </tr>
  <?php endforeach; ?>
 </tbody>
</table>
<?php DynamicFormWidget::end(); ?>




SP Sureshkumar P Syncfusion Team March 22, 2023 12:10 PM UTC

Prashant, thank you for reaching out to us with your concern. Upon reviewing the code example, you shared, we noticed that the dropdownlist component used is not a Syncfusion component, but rather a Yii Framework component. To help you resolve this issue, we recommend referring to the documentation provided by Yii Framework and posting your query on their respective forum.


You can find the relevant documentation at this link: https://www.yiiframework.com/wiki/723/creating-a-dependent-dropdown-from-scratch-in-yii2?revision=7



PS Prashant Sontale March 22, 2023 12:49 PM UTC

Thank you


Loader.
Live Chat Icon For mobile
Up arrow icon