vishva vishva - 14 days ago 13
Javascript Question

wbraganca yii2 dynamic form date picker issue?

I am using wbraganca dynamic form. In my form one field need date picker,so i use jui date picker like below

<?= $form->field($model, "[{$i}]DOB")->widget(DatePicker::classname(), [
'language' => 'en',
'options' => ['class'=>'cust-form-control dob','placeholder'=>'Date of birth','autocomplete'=>'off','readOnly'=>true,'aria-label' => 'Date of Birth'],
'clientOptions'=>[
'changeMonth'=>true,
'changeYear'=> true,
'yearRange'=> "1925:+0",
'dateFormat' => 'dd/mm/yy',
'maxDate' => "-1D",
],
])->label(false); ?>


Earlier i am face one problem, that is the date picker open only first form, if user click add button means the form will appear but datepicker does not appear, so i am add one custom script like below

$(function () {
$(".dynamicform_wrapper").on("afterInsert", function(e, item) {
$( ".dob" ).each(function() {
$( this ).datepicker({
dateFormat : 'dd/mm/yy',
yearRange : '1925:+0',
maxDate : '-1D',
language : 'en',
changeMonth: true,
changeYear: true
});
});
});


});

So date picker open all forms correctly and i am open multiple form and choose date picker one by one means it is working fine. But problem is for example, First i am open two forms and close first form, now the second form come first at that time date picker will appear but it is not clickable.

Answer

Use afterDelete and reinitialize datepicker :

$this->registerJs(' 
$(function () {
    $(".dynamicform_wrapper").on("afterInsert", function(e, item) {
        $( ".dob" ).each(function() {
           $( this ).datepicker({
              dateFormat : "dd/mm/yy",
              yearRange : "1925:+0",
              maxDate : "-1D",
              changeMonth: true,
              changeYear: true
           });
      });          
    });
});
$(function () {
    $(".dynamicform_wrapper").on("afterDelete", function(e, item) {
        $( ".dob" ).each(function() {
           $( this ).removeClass("hasDatepicker").datepicker({
              dateFormat : "dd/mm/yy",
              yearRange : "1925:+0",
              maxDate : "-1D",
              changeMonth: true,
              changeYear: true
           });
      });          
    });
});
');

You need to remove class hasDatepicker to reinitialize datepicker.