Yii的 - 在一个表单提交多个记录多个、表单、Yii

2023-09-09 21:59:47 作者:不放肆去愛怎知自己有多傻

有谁知道如何在Yii中只使用一个窗体上添加多个记录?所有记录属于同一型号和是相同格式的

Does anyone know how to add multiple records using just one form in Yii? All the records belong to the same model and are of the same format.

非常感谢,

尼克

推荐答案

的相当于batchCreate方法的BATCHUPDATE从指南可能是这样的:

The equivalent "batchCreate" method of the "batchUpdate" from the guide could be something like this:

public function actionBatchCreate() {
    $models=array();
    // since you know how many models
    $i=0;
    while($i<5) {
        $models[]=Modelname::model();
        // you can also allocate memory for the model with `new Modelname` instead
        // of assigning the static model
    }
    if (isset($_POST['Modelname'])) {
        $valid=true;
        foreach ($_POST['Modelname'] as $j=>$model) {
            if (isset($_POST['Modelname'][$j])) {
                $models[$j]=new Modelname; // if you had static model only
                $models[$j]->attributes=$model;
                $valid=$models[$j]->validate() && $valid;
            }
        }
        if ($valid) {
            $i=0;
            while (isset($models[$i])) {
                $models[$i++]->save(false);// models have already been validated
            }
            // anything else that you want to do, for example a redirect to admin page
            $this->redirect(array('modelname/admin'));
        }
    }

    $this->render('batch-create-form',array('models'=>$models));
}

这里唯一担心的是,一个新的实例有要为您节省,使用每个模型创建的。该逻辑的其余部分可以在你希望的任何方式在上面的例子可以实现,例如所有的车型都被验证,然后保存,而你可能会停止验证,如果任何模式是无效的,或者直接保存的模式,让在确认发生保存通话。因此,逻辑真的取决于你的应用程序的UX。

The only concern here is that a new instance has to be created for each model that you are saving, using new. The rest of the logic can be implemented in any way you wish, for example in the above example all the models are being validated, and then saved, whereas you could have stopped validation if any model was invalid, or maybe directly saved the models, letting validation happen during save call. So the logic will really depend on your app's ux.