Yii - 在一个表单提交中的多个记录 [英] Yii - multiple records in one form submission

查看:19
本文介绍了Yii - 在一个表单提交中的多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何在 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.

非常感谢,

尼克

推荐答案

指南中的batchUpdate" 可能是这样的:

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

这里唯一的问题是必须为您保存的每个模型创建一个新实例,使用new.其余的逻辑可以按照您希望的任何方式实现,例如在上面的示例中,所有模型都被验证,然后保存,而如果任何模型无效,您可以停止验证,或者直接保存模型,让验证在 save 调用期间发生.因此,逻辑将真正取决于您应用的用户体验.

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.

这篇关于Yii - 在一个表单提交中的多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆