php - yii 中的多模型形式

标签 php templates yii yii-cmodel yii-chtml

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

最佳答案

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

对于要收集的数据,您有两种模型。假设 PersonVehicle

第 1 步:设置用于输入表单的 Controller

在你的 Controller 中创建模型对象:

public function actionCreate() {

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

  //.. see step nr.3

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

第 2 步:编写 View 文件

//..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

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

第 3 步:在 $_POST 操作上编写 Controller

现在回到您的 Controller 并为 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
}

关于php - yii 中的多模型形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6720209/

相关文章:

php - 在子目录中部署 yii2

activerecord - 为什么每个带有activerecord的请求都在做SHOW TABLE?

c++ - 模板参数列表短路?

C++ 模板 : Calling member function of derived template class from base class

php - SQL - Yii - 如果外部条目之一匹配排序 1,如果没有则排序 2

php - 带一个PHP函数到Mysql,使用十进制数

c++ - 模板特化在其实例化点看不到函数

javascript - 将canvas图片插入MySQL数据库

php - 如何查询数据库中的所有用户及其相关数据?

php - mysql_connect() - 已弃用?使用本地主机