yii 一个表单提交多个模型数据

来源:互联网 发布:mac动态桌面壁纸软件 编辑:程序博客网 时间:2024/04/27 21:03

正在需要的时候发现了这个大牛的博文,动手实践过后,记录在此。

(原文在此)


--user表Create Table: CREATE TABLE `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `username` varchar(45) DEFAULT NULL,  `userpass` varchar(45) DEFAULT NULL,  `profile_id` int(11) DEFAULT NULL,  PRIMARY KEY (`id`),  KEY `fk_msjy_user_1_idx` (`profile_id`),  CONSTRAINT `profile_id` FOREIGN KEY (`profile_id`) REFERENCES `msjy_profile` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8--profile表Create Table: CREATE TABLE `msjy_profile` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `status` tinyint(4) DEFAULT NULL,  `address` varchar(45) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8


接下来,gii生成user和profile模型


然后gii生成RegisterController并整理成如下:

class RegisterController extends Controller{public function actionIndex(){$this->render('index');}public function actionCreate() {     $modelA = new User;     $modelB = new Profile;     if(isset($_POST['User']) && isset($_POST['Profile']))     {         $modelA->attributes=$_POST['User'];         $modelB->attributes=$_POST['Profile'];                  if($modelA->validate() && $modelB->validate())         {             if ($modelB->save(false))             {                      $modelA->profile_id = $modelB->id;                       if ($modelA->save(false))                       {                             $this->redirect(array('User/view','id'=>$modelA->id));                       }             }          }     }     $this->render('create',array(         'modelA'=>$modelA,         'modelB'=>$modelB,     )); }}

在views里的register包里创建

--create.php <?php echo $this->renderPartial('_form', array('modelA'=>$modelA,'modelB'=>$modelB)); ?>_form.php
<?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'User-form', 'enableAjaxValidation'=>false,)); ?>

Fields with * are required.

<?php echo $form->errorSummary(array($modelA,$modelB)); ?>//注意这里
<?php echo $form->labelEx($modelA,'username'); ?> <?php echo $form->textField($modelA,'username'); ?> <?php echo $form->error($modelA,'username'); ?>
<?php echo $form->labelEx($modelA,'userpass'); ?> <?php echo $form->textField($modelA,'userpass'); ?> <?php echo $form->error($modelA,'userpass'); ?>
<?php echo $form->labelEx($modelB,'status'); ?> <?php echo $form->textField($modelB,'status'); ?> <?php echo $form->error($modelB,'status'); ?>
<?php echo $form->labelEx($modelB,'address'); ?> <?php echo $form->textField($modelB,'address'); ?> <?php echo $form->error($modelB,'address'); ?>
<?php echo CHtml::submitButton($modelA->isNewRecord ? 'Create' : 'Save'); ?>
<?php $this->endWidget(); ?>
另外,关于create方法里的验证,原文有说明,此处省略文字若干。。。。。

原创粉丝点击