Adding dynamic DateControl fields from related model to a form

I have three models: User, Job and UserJob. The models User and Job have n:m relation. In the user form I need to dynamically add new jobs.

In the model User I get the jobs related to the current user:


public function getUserJobs() {

    return UserJob::find()

        ->where(['user_id' => $this->id])

        ->orderBy('start DESC')

        ->all();

}

In the views/user/_form.php are the existing jobs added to the form as follows:


if (isset($userJobs)) {

    $i = 0;

    foreach ($userJobs as $job) {

        $i++;

        ...

        echo $form->field($job, '['.$i.']start')->widget(DateControl::className(), [

            'type' => kartik\datecontrol\DateControl::FORMAT_DATE,

            'saveOptions' => [

                'name' => 'job_start[]',

            ],

        ])->label(false);

        ...

I add new jobs with jQuery (similarly as in these examples). For most fields it works perfectly. But there is a problem with the field start, which uses the DateControl extension. The extension produces its own jQuery script. Without manipulating this script the start field can not work correctly.

A possible solution is to add a few hidden rows with job-fields:


for ($j=$i; $j < $i+3; $j++) {

    $job = new MitarbeiterJob();

    echo '<tr style="display:none;" class="new_job">';

    ...

    echo $form->field($job, '['.$j.']start')->widget(DateControl::className(), [

            'type' => DateControl::FORMAT_DATE,

            'saveOptions' => [

                'name' => 'job_start[]',

            ],

        ])->label(false);

    }

    ...

If a user clicks on the button ‘Add a new job’, then a jQuery script shows one of the rows.

It works, but the solution is not optimal. (The question is also published on StackOverflow.)

[color="#006400"]/* Moved from "General Discussions" to "Extensions" */[/color]