/****
CJuiDialog for create new model http://www.yiiframework.com/wiki/145/cjuidialog-for-create-new-model/translated by php攻城師http://blog.csdn.net/phpgcsIntroduction
Scenario
Preparation of the form
Enhance the action create
The dialog
Summary
***/Introduction 本教程關于如何 用一個對話框實現一個新建界面
這有點類似 使用 Ajax 鏈接來實現目的, 但是我們將會是喲你個一個更簡單和更高效的方式:
表單的onSubmin 事件(the event onSubmit of the form)背景 Scenario 假設我們有一個很多學生的教室。 在沒有創建教室的情況下, 如果用戶想要填寫學生信息的表單, 需要先創建一個教室 并且會丟失掉之前已經輸入的學生信息。。。
我們想要允許用戶從學生表單中創建教室,而不需要更改頁面。準備表單 Preparation of the form 首先,我們要 一個創建教室的表單。 我們可以用 gii 來生成一個 crud 。。
在 普通提交的情況下,這個表單工作正常了以后, 我們可以將其用于一個 對話框。增強 創建動作 Enhance the action create
我們需要 增強 創建教室的控制器動作, 如下:public function actionCreate(){$model=new Classroom;// Uncomment the following line if AJAX validation is needed// $this->performAjaxValidation($model);if(isset($_POST['Classroom'])){$model->attributes=$_POST['Classroom'];if($model->save()){if (Yii::app()->request->isAjaxRequest){echo CJSON::encode(array('status'=>'success', 'div'=>"Classroom successfully added"));exit; }else$this->redirect(array('view','id'=>$model->id));}}if (Yii::app()->request->isAjaxRequest){echo CJSON::encode(array('status'=>'failure', 'div'=>$this->renderPartial('_form', array('model'=>$model), true)));exit; }else$this->render('create',array('model'=>$model,));}我們做了一些小改動:
在ajax 請求的情況下 我們寫了一個 json 編碼的數組。在這個數組中, 我們返回了一個狀態 , 整個表單使用 renderPartial 來創建的。現在后臺已經完成,我們來寫對話框。<?php echo CHtml::link('Create classroom', "", // the link for open the dialogarray('style'=>'cursor: pointer; text-decoration: underline;','onclick'=>"{addClassroom(); $('#dialogClassroom').dialog('open');}"));?><?php
$this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog'id'=>'dialogClassroom','options'=>array('title'=>'Create classroom','autoOpen'=>false,'modal'=>true,'width'=>550,'height'=>470,),
));?><div class="divForForm"></div><?php $this->endWidget();?><script type="text/javascript">
// here is the magic
function addClassroom()
{<?php echo CHtml::ajax(array('url'=>array('classroom/create'),'data'=> "js:$(this).serialize()",'type'=>'post','dataType'=>'json','success'=>"function(data){if (data.status == 'failure'){$('#dialogClassroom div.divForForm').html(data.div);// Here is the trick: on submit-> once again this function!$('#dialogClassroom div.divForForm form').submit(addClassroom);}else{$('#dialogClassroom div.divForForm').html(data.div);setTimeout(\"$('#dialogClassroom').dialog('close') \",3000);}} ",))?>;return false; }</script>就這些, 這些代碼我都做了些什么?1, 一個鏈接,用來打開對話框
2, 對話框本身, 其中是一個 將會被 ajax 替代的 div
3, js 函數 addClassroom()
4, 這個函數出發了一個ajax 請求, 執行了我們在前面步驟中 準備的 create classroom 的動作。
5, 在 status failure 的情況下, 返回的 form 將會 在 對話框中在 status success 的情況下, 我們將 替換 div 并在3秒后 關閉對話框你還可以返回 新插入的 classroom 的 id ,并將其植入 一個下拉列表 并自動選中。總結:準備常規的 gii 生成的 creation 動作代碼
修改 create 動作 ,增加 處理Ajax 請求的代碼
在任何地方,你可以防止 link , dialog , js 代碼此方法非常合適, 因為它changes anything in the code of the _form ,因此任何最終添加到 classroom 的 字段 都將在 標準的/對話框 的創建表單中 通用。