2012-10-16 19 views
1

我在Page.php中設置了一個名爲Color的字段,並且我想要抓取父級顏色或循環的任何子項,直到找到設置了顏色字段的父級。SilverStripe繼承父數據對象中的元素

我有一個函數,它似乎在2.4下工作,但我不能在SS3中工作,我在模板中循環調用$ Inherited(Color)。

您的幫助表示讚賞

public function Inherited($objName) { 
    $page = $this->owner->Data(); 
    do { 

     if ($obj = $page->obj($objName)) { 

      if ($obj instanceof ComponentSet) { 
       if ($obj->Count()) { 
        return $obj; 
       } 
      } elseif ($obj instanceof DataObject) { 

       if ($obj->exists()) { 
        return $obj; 
       } 
      } elseif ($obj->exists()) { 
       return $obj; 
      } 
     } 
    } while ($page->ParentID != 0 && $page = $page->Parent()); 
} 

回答

1

假設您的顏色字​​段是數據庫字段而不是與另一個數據對象的關係,請將以下方法添加到Page類中。

 
public function getColour() { 

    // Try returning banners for this page 
    $colour = $this->getField('Colour'); 
    if ($colour) { 
     return $colour; 
    } 

    // No colour for this page? Loop through the parents. 
    $parent = $this->Parent(); 
    if ($parent->ID) { 
     return $parent->getColour(); 
    } 

    // Still need a fallback position (handled by template) 
    return null; 
} 

如果顏色是相關的數據對象,你可以做同樣的事情,但在代碼中使用getComponentgetComponents方法代替getField以上。這應該適用於Silverstripe版本2.4.x和3.0.x.

這種操作儘管很有用,但應該儘可能少地執行或大量緩存,因爲它的遞歸可能發生在大多數頁面加載上,並且很少發生更改。

1

我想你已經有一些DataObjectDecorator裏面定義了這個功能,你使用$this->owner來指代當前頁面。

存在SilverStripe 3(見http://www.robertclarkson.net/2012/06/dataextension-class-replacing-dataobjectdecorator-silverstripe-3-0/)沒有更多的DataObjectDecorator那麼有兩種可能的解決方案:

一)DataExtension

B取代DataObjectDecorator)只需移動Inherited功能,以您的Page類,以及替換$this->owner$this

+0

鏈接不工作:https://web.archive.org/web/20121025022048/http://www.robertclarkson.net/2012/06/dataextension-class-replacing-dataobjectdecorator-silverstripe-3-0 – user956584

相關問題