控制器代碼:
public function actionIndex() { $model=new Staff('search'); if(isset($_GET['Manager'])) $model->attributes=$_GET['Manager']; $this->render('index',array( 'model'=>$model, )); }將model傳到CGridView,數據庫有一條記錄,但是卻不顯示。
CGridView代碼部分如下:
<?php $this->widget('zii.widgets.grid.CGridView', array( 'ajaxUpdate' => false, 'id'=>'staff-grid', 'itemsCssClass' => 'data_list', 'dataProvider'=>$model->search(), 'template' => '{items}{pager}', 'pager' => array( 'class'=>'LLinkPager', ), 'pagerCssClass' => 'myPager', 'enableSorting' => false, 'emptyText'=>'暫無數據', 'columns'=>array( ... ), )); ?>對比默認生成的代碼發現,在$model=new Staff('search');代碼下有一行代碼:$model->unsetAttributes(); 加上該代碼后,發現數據可以顯示。Why?
查看一下unsetAttributes() 方法
unsetAttributes() 方法(可用自 v1.1.3) public void unsetAttributes(array $names=NULL) $names array list of attributes to be set null. If this parameter is not given, all attributes as specified by attributeNames will have their values unset. 源碼: framework/base/CModel.php#482 (隱藏) public function unsetAttributes($names=null) { if($names===null) $names=$this->attributeNames(); foreach($names as $name) $this->$name=null; }該方法目的是將屬性設置為NULL。
測試:
public function actionIndex() { $model=new Staff('search'); var_dump($model->attributes); exit; $model->unsetAttributes(); if(isset($_GET['Manager'])) $model->attributes=$_GET['Manager']; $this->render('index',array( 'model'=>$model, )); }結果為:
array(6) { ["sector_id"]=> string(1) "0" ["password"]=> string(0) "" ["permission"]=> int(0) ["logintime"]=> int(0) ["id"]=> NULL ["username"]=> NULL }怎么sector_id值為0?原來,我在數據庫中將sector_id的默認值設為0,是不是問題在這?于是,我將該字段默認值設置為2,刷新
結果為:
array(6) { ["sector_id"]=> string(1) "2" ["password"]=> string(0) "" ["permission"]=> int(0) ["logintime"]=> int(0) ["id"]=> NULL ["username"]=> NULL }原來如此。
因為數據庫中的一條記錄,它的sector_id的值為1,你以0查詢,當然是找不到數據嘍。
掃碼二維碼 獲取免費視頻學習資料
- 本文固定鏈接: http://www.wangchenghua.com/post/4570/
- 轉載請注明:轉載必須在正文中標注并保留原文鏈接
- 掃碼: 掃上方二維碼獲取免費視頻資料
查 看2022高級編程視頻教程免費獲取