做後台時幾乎一定會遇到「分類樹」這種需求:一張展開的表格看層級,或一個下拉選單選上層分類。以下這個 Yii 擴充元件把兩種形式都包好了,樣式、格式化欄位、層級關聯欄位、表頭名稱甚至時間格式都能自訂。


<?php $this->widget('ext.tree.widgets.TreeWidget', array(
'dataProvider' => $dataProvider, // 傳入資料
'pid' => 'pid', // 設定層級關聯欄位
'tableClass' => 'items table table-striped table-bordered table-condensed', // 表格樣式
'formatParam' => 'name', // 設定要格式化的欄位
'formatTime' => array( // 設定需要格式化的時間欄位
'created'
),
'tableHead' => array( // 表格欄位名稱
'分類ID',
'頻道',
'中文名',
'英文名',
'首字母',
'排序',
'分類級別',
'父ID',
'創建時間',
),
)); ?>
<?php $this->widget('ext.tree.widgets.TreeWidget', array(
'dataProvider' => $cate, // 傳入資料
'pid' => 'pid', // 父級 ID 欄位
'formatParam' => 'name', // 要顯示的欄位
'treeType' => false, // 輸出下拉選單而非表格
'selectClass' => 'class="span11"', // 下拉選單樣式
'defaultSelectValue' => array( // 預設值與提示選項
0, '≡ 作為一級欄目 ≡'
),
)); ?>
<?php
/**
* 分類樹元件
* 支援表格與下拉選單兩種輸出形式
*/
class TreeWidget extends Widget {
/** 元件接收的資料:CArrayDataProvider 物件或陣列 */
public $dataProvider;
/** 完整資料集合 */
public $arrAll = array();
/** 以 _ID 為鍵名的多維父子關係 */
public $arrIdRelation = array();
/** 上述關係的簡化版,用於輸出樹狀結構 */
public $arrIdRelationSimple = array();
/** 以 _ID 為鍵名的原始資料索引 */
public $arrIdAll = array();
/** 所有父子對應 */
public $arrIdSon = array();
/** 葉節點的 _ID */
public $arrIdLeaf = array();
/** 根節點的 _ID */
public $arrIdRoot = array();
/** 每個節點底下所有後代節點的 _ID */
public $arrIdChildren = array();
/** 每個節點回溯到根的路径 */
public $arrIdBackPath = array();
/** 單行輸出的樣板 */
public $strItem = '<br />{$strSep}{$name}';
/** 表格樣式 */
public $tableClass = 'items table table-striped table-bordered table-condensed';
/** 資料欄位名稱陣列 */
public $dataKey = array();
/** 指定要格式化的欄位 */
public $formatParam = 'name';
/** 表格欄位標題 */
public $tableHead = array();
/** 父級 ID 欄位名稱 */
public $pid = 'pid';
/** true:表格樹;false:下拉選單樹 */
public $treeType = true;
/** 下拉選單 option 綁定的值欄位 */
public $optionValue = 'id';
/** 需要格式化的時間欄位 */
public $formatTime = array();
/** 下拉選單樣式 */
public $selectClass = 'class="span3"';
/** 下拉選單的預設值與第一個選項 */
public $defaultSelectValue = array(
0, '≡ 作為一級欄目 ≡',
);
/** 下拉選單是否多選 */
public $isMultiple = false;
/** 下拉選單已選中的值 */
public $bindSelectValue = 0;
/** 執行元件 */
public function run() {
if (is_array($this->dataProvider) && count($this->dataProvider) > 0)
$data = $this->_run($this->dataProvider);
else if (is_object($this->dataProvider) && count($this->dataProvider->rawData) > 0)
$data = $this->_run($this->dataProvider->rawData);
$this->render('tree', array('data' => $data));
}
/** 依型態決定輸出表格或下拉選單 */
private function _run($datas){
foreach ($datas as $data)
$this->arrAll[] = $data;
$this->dataKey = array_keys($data);
$this->processData();
if ($this->treeType === true)
$data = $this->getTable();
else
$data = $this->getSelect($this->pid, $this->bindSelectValue,
$this->isMultiple, $this->selectClass,
$this->defaultSelectValue);
return $data;
}
/** 取得 HTML */
public function getHtml() {
return $this->genHtml();
}
/** 表格型態下的單行樣板 */
public function getItemName(){
$html = '<tr>';
foreach($this->dataKey as $v) {
$str = ($this->formatParam == $v) ? '{$strSep}' : '';
$html .= '<td>'.$str.'{$'.$v.'}</td>';
}
$html .= '</tr>';
return $html;
}
/** 表格標題列 */
public function getTableHead(){
$html = '<tr>';
foreach($this->tableHead as $v)
$html .= '<th>'.$v.'</th>';
$html .= '</tr>';
return $html;
}
/** 產生完整的表格樹 */
public function getTable() {
$this->strItem = $this->getItemName();
$strRe = '<table class="'.$this->tableClass.'">';
$strRe .= '<thead>'.$this->getTableHead().'</thead><tbody>';
$strRe .= $this->genHtml();
$strRe .= '</tbody></table>';
return $strRe;
}
/** 產生下拉選單樹 */
public function getSelect($strName = 'tree', $arrValue = array(), $blmMulti = false,
$strExt = '', $arrFirst = null) {
!is_array($arrValue) && $arrValue = array($arrValue);
foreach ($this->arrIdAll as $strTemp => $arrTemp) {
$this->arrIdAll[$strTemp]['selected'] = '';
if (in_array($arrTemp['id'], $arrValue)) {
$this->arrIdAll[$strTemp]['selected'] = ' selected="selected"';
}
}
$this->strItem = '<option value="{$'.$this->optionValue.'}"{$selected} '
. 'title="{$'.$this->formatParam.'}">{$strSep}{$'.$this->formatParam.'}</option>';
$strRe = '<select id="id_' . $strName . '" name="' . $strName . ($blmMulti ? '[]' : '') . '"';
$strRe .= ($blmMulti ? ' multiple="multiple"' : '') . (empty($strExt) ? '' : ' ' . $strExt) . '>';
if (is_array($arrFirst) && count($arrFirst) == 2) {
$strRe .= '<option value="' . $arrFirst[0] . '">' . $arrFirst[1] . '</option>';
}
$strRe .= $this->getHtml() . '</select>';
return $strRe;
}
/** 遞迴建立父子關係 */
private function helpForGetRelation($arrData) {
$arrRe = array();
foreach ($arrData as $strTemp => $arrTemp) {
$arrRe[$strTemp] = $arrTemp;
if (isset($this->arrIdRelation[$strTemp])) {
$arrRe[$strTemp] = $this->arrIdRelation[$strTemp];
}
if (count($arrRe[$strTemp]) > 0) {
$arrRe[$strTemp] = $this->helpForGetRelation($arrRe[$strTemp]);
} else {
array_push($this->arrIdLeaf, $strTemp);
}
}
return $arrRe;
}
/** 收集節點底下所有後代 */
private function helpForGetChildren($arrData) {
$arrRe = array_keys($arrData);
foreach ($arrData as $arrTemp) {
$arrRe = array_merge($arrRe, $this->helpForGetChildren($arrTemp));
}
return $arrRe;
}
/** 回溯節點到根的路径 */
private function helpForGetBackPath($str) {
$arrRe = array();
$intTemp = $this->arrIdAll[$str][$this->pid];
if ($intTemp > 0) {
$intTemp = '_' . $intTemp;
array_push($arrRe, $intTemp);
$arrRe = array_merge($arrRe, $this->helpForGetBackPath($intTemp));
}
return $arrRe;
}
/** 資料前處理 */
private function processData() {
$count = count($this->arrAll);
foreach ($this->arrAll as $arrTemp) {
$strTemp = '_' . $arrTemp['id'];
$this->arrIdAll[$strTemp] = $arrTemp;
if ($arrTemp[$this->pid] > 0 && $count > 1) {
$strTemp_ = '_' . $arrTemp[$this->pid];
!isset($this->arrIdRelation[$strTemp_]) && $this->arrIdRelation[$strTemp_] = array();
$this->arrIdRelation[$strTemp_][$strTemp] = array();
!isset($this->arrIdSon[$strTemp_]) && $this->arrIdSon[$strTemp_] = array();
array_push($this->arrIdSon[$strTemp_], $strTemp);
} else {
!isset($this->arrIdRelation[$strTemp]) && $this->arrIdRelation[$strTemp] = array();
array_push($this->arrIdRoot, $strTemp);
}
}
$this->arrIdRelation = $this->helpForGetRelation($this->arrIdRelation);
$this->arrIdLeaf = array_unique($this->arrIdLeaf);
foreach ($this->arrIdRelation as $strTemp => $arrTemp) {
$this->arrIdChildren[$strTemp] = $this->helpForGetChildren($arrTemp);
in_array($strTemp, $this->arrIdRoot) && $this->arrIdRelationSimple[$strTemp] = $arrTemp;
}
$arrTemp = array_keys($this->arrIdAll);
foreach ($arrTemp as $strTemp) {
$this->arrIdBackPath[$strTemp] = $this->helpForGetBackPath($strTemp);
}
}
/** 產生層級分隔線 */
private function genSeparator($intLen) {
$strRe = '';
$i = 0;
while ($i < $intLen) {
$strRe .= ' ' . (($i + 1 == $intLen) ? '├' : '│');
$i++;
}
!empty($strRe) && $strRe .= '─';
return $strRe;
}
/** 遞迴輸出整棵樹,同時處理時間格式化 */
private function genHtml($arrRelation = null, $intSep = 0) {
$strRe = '';
null === $arrRelation && $arrRelation = $this->arrIdRelationSimple;
foreach ($arrRelation as $strKey => $arrTemp) {
if (count($this->arrIdAll[$strKey]) > 0) {
if (!empty($this->formatTime) && count($this->formatTime) > 0) {
foreach($this->formatTime as $formatTime) {
if ($this->arrIdAll[$strKey][$formatTime] > 0) {
$this->arrIdAll[$strKey][$formatTime] =
date('Y-m-d H:i:s', $this->arrIdAll[$strKey][$formatTime]);
}
}
}
$strSep = $this->genSeparator($intSep);
extract($this->arrIdAll[$strKey]);
eval('$strRe .= "' . $this->strItem . '";');
count($arrTemp) > 0 && $strRe .= $this->genHtml($arrTemp, ($intSep + 1));
}
}
return $strRe;
}
}
?>
<?php if (!empty($data)): ?>
<?php echo $data; ?>
<?php else: ?>
<tr><td colspan="4" class="empty"><span class="empty">沒有找到數據.</span></td></tr>
<?php endif; ?>
這個元件最方便的地方在於資料來源很隨意——陣列或 CArrayDataProvider 都能吃,所以無論資料是剛查出來還是經過分頁,都可以直接丟進去。另外 genHtml() 中使用了 eval 來套用具名字串,彈性很高但伴隨風險:如果 formatParam 指定的欄位內容來自使用者輸入且未消毒,就可能形成程式碼注入。正式環境建議把樣板替換改成 str_replace 或 sprintf 一類的做法。