简体   繁体   English

Yii2 同一模型的多个实例与 javascript

[英]Yii2 multiple instances of the same model with javascript

I am trying to use multiple instances of the same model using javascript append.我正在尝试使用 javascript append 使用同一模型的多个实例。 However, I do not know how to do that.但是,我不知道该怎么做。 Therefore, I create the following code.因此,我创建了以下代码。

javascript javascript

var div_input = $('#input');
div_input.append('<input type="hidden" name="'+c+'_round" value="'+c+'" />');

variable "c" is a increasing running number.变量“c”是一个递增的运行数。 for example, first time i append the name will be "1_round".例如,我第一次附加名称将是“1_round”。 and second time will be "2_round" and so on.第二次将是“2_round”,依此类推。

Controller控制器

 $loop = true;
    $i = 0;
    do{
        $i++;
        if (!empty($_POST[$i . "_round"]))
        {
            $round = $_POST[$i . "_round"];
            $model->model_round= $round;
            $model->save();
        }else{
            $loop = false;
        }
    }while($loop);

The problem here is it will always only save the last loop of data and not every loop of data.这里的问题是它总是只保存最后一个数据循环而不是每个数据循环。 Please help me with this.请帮我解决这个问题。 New to Yii2. Yii2 的新手。 Thanks!谢谢!

You have to initialize new instance of $model each time in loop您必须每次在循环中初始化$model新实例

ie

    $saved_array = [];
    $loop = true;
    $i = 0;
    do{
        $i++;
        if (!empty($_POST[$i . "_round"]))
        {
            $model = new model();
            $round = $_POST[$i . "_round"];
            $model->model_round= $round;
            if($model->save()) {
                $saved_array[$model->id] = True;
            } else {
                $saved_array[$model->id] = $model->getErrors();
            }
            unset ($model);
        }else{
            $loop = false;
        }
    }while($loop);

You can finally analyize if model is saved or not if not saved what are the errors with the $saved_array您最终可以分析模型是否已保存,如果未保存,则$saved_array有哪些错误

Why don't you use input name as array为什么不使用输入名称作为数组

<input name="round[]">

Then loop it然后循环

$round = $_POST['round'];
foreach( $round as $key => $n ) {
// code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM