Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

activerecord - Yii - multiple records in one form submission

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.

Many thanks,

Nick

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...