Yii2: Adding dynamic DateControl fields from related model to a form

风格不统一 提交于 2019-12-25 04:38:20

问题


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.

Is there a way how to dynamically add new DateControl fields to the form?


回答1:


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...



来源:https://stackoverflow.com/questions/36130867/yii2-adding-dynamic-datecontrol-fields-from-related-model-to-a-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!