2014-11-03 25 views
0

我正在使用Yii的CGridView(實際上它是yiistrap的TbGridView),我創建了一個帶有一個listen按鈕的自定義CButtonColumn模板,一切正常,直到我發現自己將這些代碼複製到每個需要表列表的偵聽按鈕的地方。如何製作Yii CButtonColumn自定義按鈕全局?

array(
     'class'=>'bootstrap.widgets.TbButtonColumn', 
     'template'=>'{listen}{delete}', 
     'buttons'=>array(
      'listen'=>array(
       'label'=>'listen', 
       'options' => array('class'=>'view headphones'), 
       'icon' => 'icon-headphones', 
       'url' => '#', 
       'visible' => '$data->filename_32', 
      ), 
     ), 
    ), 

有什麼我可以做的,使這一小塊代碼全局配置?如:

array(
    'template'=>'{listen}{delete}', 
    'buttons'=>array(
     'listen' => 'xxxx.widgets.buttons.Listen', 
    ) 
) 

就是這樣。

+0

你爲什麼不使用小工具?將視圖放在組件文件夾中,創建適當的控制器,然後在一行代碼中調用視圖:) – 2014-11-03 09:42:59

回答

1

你可以!在你的config/main.php,添加:

'components' => array(
    'widgetFactory' => array(
     'widgets' => array(
      'bootstrap.widgets.TbButtonColumn' => array(
       'template' => '{listen}{delete}', 
       'buttons' => array(
        'listen' => 'xxxx.widgets.buttons.Listen', 
       ) 
      ), 
     ) 
    ) 
), 

這種方法主要用於雖然預配置的內部部件,在情況下,你無法控制的精確類會被加載widget的。在你的情況下,它看起來像您指定的窗口小部件類名手動了,所以乾脆重寫TbButtonColumn小部件可能是一個更容易和更清潔的解決方案:

class MyTbButtonColumn extends TbButtonColumn { 
    public $template = '{listen}{delete}'; 

    public $buttons = array(
     'listen' => 'xxxx.widgets.buttons.Listen', 
    ); 
} 

array(
    'class' => 'MyTbButtonColumn', 
), 
+0

但是,我看到,最大的問題是,如何正確編寫'xxxx.widgets.buttons.Listen'?我找不到'CButton',我可以自由擴展並創建自己的「ListenButton」類,這令人沮喪,不管我做什麼,我只是保持重複'''array( 'label'=>'listen' 'options'=> array('class'=>'view headphones'), 'icon'=>'icon-headphones', 'url'=>'#', 'visible'=>'$ data - > filename_32', ),''' – 2014-11-05 02:21:39

+0

@ChrisPeng啊,對,它看起來像Yii1中沒有類似「Button」類的東西,buttons屬性是一個普通數組。 但是你可以簡單地在你的MyTbButtonColumn中定義這樣一個數組,不是嗎? '類MyTbButtonColumn延伸TbButtonColumn { 公共$按鈕=陣列( \t '聽'=>數組( '標籤'=> '聽', \t ... ' – david 2014-11-07 17:55:23