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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With