標籤:style blog http color os 資料
正在需要的時候發現了這個大牛的博文,動手實踐過後,記錄在此。
--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<div class="form"><?php $form=$this->beginWidget(‘CActiveForm‘, array( ‘id‘=>‘User-form‘, ‘enableAjaxValidation‘=>false,)); ?> <p class="note">Fields with <span class="required">*</span> are required.</p> <?php echo $form->errorSummary(array($modelA,$modelB)); ?>//注意這裡 <div class="row"> <?php echo $form->labelEx($modelA,‘username‘); ?> <?php echo $form->textField($modelA,‘username‘); ?> <?php echo $form->error($modelA,‘username‘); ?> </div> <div class="row"> <?php echo $form->labelEx($modelA,‘userpass‘); ?> <?php echo $form->textField($modelA,‘userpass‘); ?> <?php echo $form->error($modelA,‘userpass‘); ?> </div> <div class="row"> <?php echo $form->labelEx($modelB,‘status‘); ?> <?php echo $form->textField($modelB,‘status‘); ?> <?php echo $form->error($modelB,‘status‘); ?> </div> <div class="row"> <?php echo $form->labelEx($modelB,‘address‘); ?> <?php echo $form->textField($modelB,‘address‘); ?> <?php echo $form->error($modelB,‘address‘); ?></div><div class="row"></div><div class="row buttons"><?php echo CHtml::submitButton($modelA->isNewRecord ? ‘Create‘ : ‘Save‘); ?></div> <?php $this->endWidget(); ?></div>
另外,關於create方法裡的驗證,原文有說明,此處省略文字若干。。。。。