4

I have problem with kartik select2 widget. I am trying to create dynamic form with jquery. First, I created two fields with kartik select2 in div element. Then I cloned all content of the div and append it into the div. But, cloned select2 not working when it will be clicked. Could you help me? enter image description here

Code: codes in a javascript file:

$(document).ready(function(){
    $(document).on("click", "#add-department-btn", function(e){
      e.preventDefault();
      console.log("Clicked");

      var option_name = Math.random()*1000000;
      option_name = parseInt(option_name);
      var id = $(".add-departments-container .copyPattern").data('id');
      var row = $(".add-departments-container .copyPattern").clone().removeClass('copyPattern');

      row.appendTo(".add-departments-container");

      return false;
   });
});

_form.php file:

<div class="row">
                <a href="javacript:void(0)" id="add-department-btn">+ Qo'shish</a>
            </div>  
            <div class="add-departments-container">
                <?= Yii::$app->controller->renderPartial('department/_department', [
                    'departments' => $departments,
                    'allDepartments' => $allDepartments,
                    'model' => $newDepartments,
                    'university' => $model,
                    'allLevels' => $allLevels,
                    'class' => 'copyPattern'
                    ]); ?>
            </div> 

_department.php file:

<div class="<?= $class ?>" data-id="">
    <div class="row">
        <div class="col-md-5">
            <?= Html::label('Fakultet', 'University['. $id .'][departments]') ?>
            <?= Select2::widget([
                'name' => 'University['. $id .'][departments]',
                'value' => '',
                'data' => $allDepartments,
                'options' => ['placeholder' => 'Select department ...', 'id' => 'department-'.$id],
            ]); ?>
        </div>
        <div class="col-md-5">
            <?= Html::label('Levels', 'University['. $id .'][departments]') ?>
            <?= Select2::widget([
                'name' => 'University['. $id .'][levels]',
                // 'value' => ArrayHelper::getColumn($levels->departments, 'department_id'),
                'data' => $allLevels,
                'options' => ['multiple' => true, 'placeholder' => 'Select states ...', 'id' => 'university-levels-'.$id],
                'pluginOptions' => [
                        'allowClear' => true,
                        'tags'=>true,
                        'maximumInputLength'=>10,
                    ],
            ]); ?>
        </div>
        <div class="col-md-2">
            <a href="javacript:void(0)" id="delete-department-btn">Delete</a>
        </div>
    </div>
</div>
Alisher Nasrullayev
  • 565
  • 1
  • 6
  • 22

1 Answers1

3

You can resolve this issue by doing some tricks:

1) You can pass ajax request for action thats return an html select2 widget, also you can build an ajax action that return your tabular on every click button...this will work in both case. This example from real project (this example if build ajax page for full tabular page):

public function actionGetCcForm($index)
    {
        $model              = new CalculatorsForm;
        return $this->renderAjax('calculators/_cc_foods_tabular', [
            'index' => $index,
            'model' => $model
        ]);
    }

// view page
<?php
$tabularAjax = Url::toRoute('/nutritionfacts/get-cc-form', true);
$this->registerJs(<<<JS
    $(document).on('click', '#add-new-meal',function(e) {  
        $.ajax({
           url: '$tabularAjax',
           data: {'index': currentIndex},
           success: function(data) {
               $('#_cc_foods_tabular').append(data);
           }
        });
    });
JS
, \yii\web\View::POS_END) ?>

// _cc_foods_tabular - this page will contain form
<div class="col-xs-10 col-md-3 form-group">
        <?php
            echo Select2::widget([
                'model' => $model,
                'attribute' => "[{$index}]food_id",
                'data' => $foodDependanceOfCat,
            ]);
        ?>
    </div>

2) You can return select2 data to view in (render action) like render(..., ['select2Data' => $yourSelect2Data]) and then create select2 by js like

$('#you-news-id-select').select2();

Note: this issue happen since every select2 has a unique id, this id has been trigger & assign for created selected....

Anees Hikmat Abu Hmiad
  • 3,460
  • 2
  • 19
  • 36