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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…