且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-24 10:28:22

的相当于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.