yii中的多模型形式

New*_*ser 16 php templates yii yii-cmodel yii-chtml

如何在Yii中创建多模型表单?我搜索了Yii的整个文档,但没有得到任何有趣的结果.有人可以给我一些方向或想法吗?任何帮助都会很明显.

bri*_*iiC 19

在我的经验中,我得到了这个解决方案,并且很快就能理解

您有两种模型可用于收集数据.比方说PersonVehicle.

第1步:设置控制器以输入表格

在您的控制器中创建模型对象:

public function actionCreate() {

  $Person = new Person;
  $Vehicle = new Vehicle;

  //.. see step nr.3

  $this->render('create',array(
        'Person'=>$Person,
        'Vehicle'=>$Vehicle)
  );
}
Run Code Online (Sandbox Code Playgroud)

第2步:编写视图文件

//..define form
echo CHtml::activeTextField($Person,'name');
echo CHtml::activeTextField($Person,'address');
// other fields..

echo CHtml::activeTextField($Vehicle,'type');
echo CHtml::activeTextField($Vehicle,'number');

//..enter other fields and end form
Run Code Online (Sandbox Code Playgroud)

在你的视图中放置一些标签和设计;)

第3步:编写控制器on $_POST操作

现在回到你的控制器并为POST动作编写功能

if (isset($_POST['Person']) && isset($_POST['Vehicle'])) {
    $Person = $_POST['Person']; //dont forget to sanitize values
    $Vehicle = $_POST['Vehicle']; //dont forget to sanitize values
    /*
        Do $Person->save() and $Vehicle->save() separately
        OR
        use Transaction module to save both (or save none on error) 
        http://www.yiiframework.com/doc/guide/1.1/en/database.dao#using-transactions
    */
}
else {
    Yii::app()->user->setFlash('error','You must enter both data for Person and Vehicle');
 // or just skip `else` block and put some form error box in the view file
}
Run Code Online (Sandbox Code Playgroud)