简体   繁体   中英

YII model to handle more than one table

I am developing a registration form in YII. In my form there is a radio option to choose register as Mode1 or register as Mode2. If user chooses mode1, data's should be entered to table1 or it should entered to table2. In YII each model deals with one table. Here my form deals with two tables.

So how to handle such a form to validate and enter data's to table in YII?

The easiest way is to create one model for the form (assuming they have the same fields?) This class would extend CFormModel (in the example below I refer to this model as GlobalFormModel )

This model would have the same attributes as the other two models, as well as one new attribute called mode When the form is submitted, in the controller you can handle it based on which mode and validate it against the correct model, eg:

$model = new GlobalFormModel

if(isset($_POST['GlobalFormModel'])){
    $model->attributes = $_POST['GlobalFormModel']; 

    if ($model->mode == 1){
        $newmodel = new FormOne;
        $newmodel->attributes = $model->attributes;
    } else {
         $newmodel = new FormTwo;
         $newmodel->attributes = $model->attributes;
    } 

    ... // validate and save $newmodel
}

$this->render("yourview",array("model"=>$model));

Where FormOne is the model associated with the first table, and FormTwo is associated with the second table. First you create a new instance of the GlobalFormModel (which is passed to the view). You check if the form has been submitted (you could validate it here or after loading one of the two models, that is your choice). You check the mode, and then load the correct model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM