作者:mobiledu2502938577 | 来源:互联网 | 2013-06-07 16:12
这是一个程序员经常遇到的情况。例如,这些复选框的目的,是为删除这些选中的记录。首先让我们定义一个很有用的'polymorphic'form。我相信你将会使用它了吧!
这是一个程序员经常遇到的情况。例如,这些复选框的目的,是为删除这些选中的记录。
首先让我们定义一个很有用的'polymorphic' form。我相信你将会使用它了吧!
/**
* PolymorphicForm.php in 'models' directory */ class PolymorphicForm extends CFormModel { private $data = array(); public function __get($key) { return (isset($this->data[$key]) ? $this->data[$key] : null); } public function __set($key, $value) { $this->data[$key] = $value; } } ?>
继续模型,让我们定义在一个表'Example'中定义这些字段:keyExample,Field_one,Field_two。 你知道如何做,不是吗?…
然后在控制器ExampleAction.php,动作中处理表'Example'的列表
... // an over simplified 'list' action public function actionList () { $form = new PolymorphicForm; $this->render("list", array( "models" => Example::model()->findAll(), "form" => $form, )); } ...
然后在文件list.php定义视图
<script language="Javascript"> function byebye () { // need a confirmation before submiting if (confirm('Are you sure ?')) $("#myForm").submit (); } $(document).ready(function(){ // powerful jquery ! Clicking on the checkbox 'checkAll' change the state of all checkbox $('.checkAll').click(function () { $("input[type='checkbox']:not([disabled='disabled'])").attr('checked', this.checked); }); });
script>
php echo CHtml::beginForm("index.php?r=Example/delete", "post", array("id"=>"myForm")); ?> <table>
<tr>
<th>php echo "Blabla" ?>th>
<th>php echo "Blabla bis"; ?>th>
<th> All php echo CHtml::activeCheckBox($form, "checkAll", array ("class" => "checkAll")); ?> <button type="button" onClick="byebye()" > Delete button>
th>
tr>
php foreach($models as $n=>$rec): ?> <tr>
<td>
php echo CHtml::encode($rec->Field_one); ?> td>
<td>
php echo CHtml::encode($rec->Field_two); ?> td>
<td>
php echo CHtml::activeCheckBox($form, "checkRecord_$rec->keyExample"); ?> td>
tr>
php endforeach; ?> table>
php echo CHtml::endForm(); ?>
最后,我们巧妙的来处理这些在ExampleAction.php的checkboxs:
... /**
* Deletes a range of model
* If deletion is successful, the browser will be redirected to the "list" page. */ public function actionDelete() { // I want a post if(Yii::app()->request->isPostRequest) { // parse $_POST variables foreach($_POST["PolymorphicForm"] as $key => $val) { // is one a these checkbox ? if (strstr ($key, "checkRecord")) { // checkbox in state checked ? if ($val == 1) { // get the key of the record $ar = explode ("_", $key); // deleting record $model = Example::model()->findByPk ($ar[1])->delete (); } } } $this->redirect(array("list")); } else throw new CHttpException(400,"Invalid request. Please do not repeat this request again."); } ...
结果测试,我们访问http://myHttpServer/myApp?r=Example/list可以检验
我希望这将对一些Yii程序员特别有帮助。