Yii2:将来自相关模型的动态DateControl字段添加到表单 [英] Yii2: Adding dynamic DateControl fields from related model to a form

查看:50
本文介绍了Yii2:将来自相关模型的动态DateControl字段添加到表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个模型:User,Job和UserJob.用户和作业模型具有n:m关系.在用户表单中,我需要动态添加新作业.

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();
}

在views/user/_form.php中,将现有作业添加到表单中,如下所示:

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

我使用jQuery添加个工作(类似于这些示例).对于大多数领域,它都可以完美地工作.但是字段 start 存在问题,该字段使用 DateControl 扩展名.该扩展产生自己的jQuery脚本.如果不操作此脚本,则开始字段将无法正常工作.

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.

有没有一种方法可以动态地向表单中添加新的DateControl字段?

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

推荐答案

一种可能的解决方案是添加一些带有作业字段的隐藏行:

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);
    }
    ...

如果用户单击添加新作业"按钮,则jQuery脚本将显示其中一行.

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

这篇关于Yii2:将来自相关模型的动态DateControl字段添加到表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆