yii中的多模型形式

时间:2011-07-16 21:02:52

标签: php templates yii yii-cmodel yii-chtml

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

4 个答案:

答案 0 :(得分:19)

在我的经验中,我得到了这个解决方案,并且可以快速理解

您希望收集的数据有两种模型。我们说PersonVehicle

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

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

public function actionCreate() {

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

  //.. see step nr.3

  $this->render('create',array(
        'Person'=>$Person,
        'Vehicle'=>$Vehicle)
  );
}

第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

在视图中添加一些标签和设计;)

第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
}

答案 1 :(得分:3)

答案 2 :(得分:2)

您不需要多模型。正确使用MVC模式需要一个反映您的UI的模型。

要解决此问题,您必须使用CFormModel而不是ActiveRecord将数据从View传递到Controller。然后在你的Controller中你将解析模型,CFormModel,并使用ActiveRecord类(多个)保存在数据库中。

Yii权威指南中的

Forms OverviewForm Model章节包含一些细节和示例。

答案 3 :(得分:1)

另一个建议 -

我们也可以使用向导行为,这是一个简化多步骤表单处理的扩展。我们可以使用多模型表格进行注册流程或其他流程。

演示 - http://wizard-behavior.pbm-webdev.co.uk/