Save multiple tabular input in Yii

2019-07-29 06:40发布

问题:

I'm wondering how can I insert tabular data in Yii.

Of course, I've followed docs in this aspect however there are few differences in my situation.

First of all, I want to save two models, exactly as in the docs article. The main difference is that there might be more that one element for second model (simple one to many relation in database).

I use CHtml to build my forms. I implemented a jQuery snippet to add more input groups dynamically.

I'm unable to show my code now as it's totally messed up and not working currently.

My main question is: how to handle the array of elements for second model in Yii?

回答1:

Define your two models in controller

$model1= new Model1();
$model2= new Model2();

//massive assignments
$model1->attributes=$_POST['Model1']
$model2->attributes=$_POST['Model2']

//validation
$valid= $model1->validate();
$valid =$valid &&  $model2->validate();

if($valid){
   $model1->save(false);
   $model1->save(false);  
  }

if you want to access fields individually dump your post and you can view the the post array format or instead of doing massive assignments you can manually assign like this

$model1->field1 =$_POST['Model1']['field1'];

//validation  logic
...  
 if($valid){
   $model1->save(false);
   $model1->save(false);  
  }


标签: php yii