如何使用单个表单来收集yii中两个或多个模型或控制器的数据

时间:2014-04-01 06:59:14

标签: php yii

在这个项目中,有两个模型

1)注册(注册:PK)

2)登录(log_id:PK和reg-id:FK)

两种模型都使用单一形式,名为views-> register-> _form.php

RegisterContoller.php

public function actionView($id)
{
        $model=$this->loadModel($id);
    $this->render('view',array(
        'model'=>$model,
                    'modelLogin'=>$model->logins,

    ));
}

public function actionCreate()
{
    $model          =   new Register;
            $modelLogin =   new Login;
            $modelGenerate  =   new Generate;

            $row            =   Generate::model()->findByPk('1') ;
            $gen_reg        =   $row['gen_reg'];
            $gen_log        =   $row['gen_log'];
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['btnRegister']))
    {
        $model->attributes=$_POST['Register'];
                    $modelLogin->attributes=$_POST['Login'];
                    $modelLogin->reg_id=$model->reg_id;

        $valid  =   $model->validate();
        $valid  =   $modelLogin->validate() && $valid;


        if($model->save()&& $modelLogin->save())
            $this->redirect(array('view','id'=>$modelLogin->log_id)
                                    );
    }

    $this->render('create',array(
                'model'=>$model,
                'modelLogin'=>$modelLogin,
                'gen_reg'=>$gen_reg,
                'gen_log'=>$gen_log
    ));
}

Register.php

public function relations()
{
    return array(
        'logins' => array(self::HAS_MANY, 'Login', 'reg_id'),
    );
}

view.php

<?php
/* @var $this RegisterController */
/* @var $model Register */
$modelLogin=new Login;
$this->breadcrumbs=array(
    'Register'=>array('index'),
    $model->reg_id,
);

$this->menu=array(
    array('label'=>'List Register', 'url'=>array('index')),
    array('label'=>'Create Register', 'url'=>array('create')),
    array('label'=>'Update Register', 'url'=>array('update', 'id'=>$model->reg_id)),
    array('label'=>'Delete Register', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->reg_id),'confirm'=>'Are you sure you want to delete this item?')),
    array('label'=>'Manage Register', 'url'=>array('admin')),
);
?>

<h1>View Register #<?php echo $model->reg_id; ?></h1>

<?php $this->widget('zii.widgets.CDetailView', array(
    'data'=>$model,
    'attributes'=>array(
        'reg_id',
        'username',
        'mobile',
    ),
)); ?>

<?php $this->widget('zii.widgets.CDetailView', array(
    'data'=>$modelLogin,
    'attributes'=>array(
        'password',
                'email',
    ),
)); ?>

输出:

查看注册#10

Reg:10

用户名:lekhulal

手机:999999999

Paswword:未设置

电子邮件:未设置

登录模型字段无效,未设置。我该怎么办?

0 个答案:

没有答案