2014-07-14 14 views
2

我最近使用yii的get方法創建虛擬屬性,向我的CGridView添加了自定義列。我創建的虛擬屬性看起來像這樣並按預期工作。當使用自定義列時,訂單按鈕不能用於CGridView - yii

public function getNumIndv() 
    { 
     // gets the id of the current list 
     $list_id = $this->id; 
     // returns the number of recipients with that list id 
     return $count = Recipient::model()->count(array("condition"=>"list_id = $list_id")); 

    } 

從那裏我的GridView我添加了自定義列 「numindv」 像這樣

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'paylist-grid', 
    'dataProvider'=>$dataProvider, 
    'filter'=>$model, 
    'columns'=>array(
     'name', 
     'numindv', 
     'balance', 
     'due_date', 

     /* 
     'status', 
     */ 
     array(
      'class'=>'CButtonColumn', 
      'template'=>'{Manage}', 
      'buttons'=>array 
      (
       'Manage' => array 
       (
        'label'=>'Manage', 
        'url'=>'Yii::app()->createUrl("recipient/index", array("id"=>$data->id))', 
       ), 

      ) 
     ), 
    ), 
)); ?> 

可正常工作 - 幾乎當用戶查看錶單時,他們看到三列「名稱,餘額和到期日期」未點亮。同樣,如果你點擊它們,它們會點亮並被分類。但對於numindv, 列自動點亮,並且而不是允許個人單擊它以更改順序。有什麼簡單的,我在這裏失蹤?爲什麼我的網格視圖將我的虛擬列視爲與其他列不同?

回答

1

你不能使用自定義列在CActiveDataProvider中排序。

您可以通過使用這種方法使numindv列標題鏈接:

$sort = new CSort(); 
$sort->attributes = array(
    'numindv' => 'numindv', 
    '*' // all other columns 
); 

$dataProvider->sort = $sort; 

但你仍然沒有得到想要的結果,因爲當你點擊這個排序鏈接它的名字將會在SQL查詢中添加:

SELECT * FROM `recipient` `t` ORDER BY `t`.`numindv`... 

但是你的表沒有列numindv。我們建議您使用CArrayDataProvider

UPD:

你可以爲這個排序設置SQL規則:

$sort->attributes = array(
    'numindv' => array(
     'asc'=>"numindv asc", 
     'desc'=>"numindv desc", 
    ), 
    '*' // all other columns 
); 

而且在Recipient::search()方法,你應該加入這一行:

$criteria->select .= ', (/*any SQL request to retrieve the numindv value*/) as numindv'; 
+0

兩個簡單的問題 1。 「你使用CArrayDataProvider」是什麼意思,你是說我應該嘗試添加一個數據字段,它需要numindv?如何做到這一點? 2.當你設置$ dataProvider-> sort = $ sort時,應該在哪裏找到它?在控制器中還是在GridView中? – Stephen

+0

1.您可以編寫返回數組的SQL查詢,並根據此數組創建用於生成網格的CArrayDataProvider。在這種情況下,你應該爲每一行獲得'numindv'值。爲了達到這個目的,你可以在執行SQL查詢之後使用一個循環,或者在查詢中附加提取這個值。我想通過SQL查詢來獲得'numindv'值,你應該在select查詢中執行:SELECT *,(SELECT COUNT(id)FROM'recipient' WHERE list_id = r.id)AS numindv' FROM'recipient' r。 2.無論它在哪裏。唯一的條件 - 它應該位於CGridView小部件之前。 – Goodnickoff

相關問題