我怎么能得到父元素属性之前,我保存和发布在Silverstripe元素的子元素


How can I get the parent element property before I save and published the children element in Silverstripe Elemental?

我在使用silverstripe元素时遇到了一点问题。我试图在子元素中获得一些父元素属性,但只有在我保存并发布子元素之后,父元素属性才可用。

例如,我想在子元素QuizAnswer中获得QuizQuestion元素属性QuestionNumber = 2,但我只在数据库中获得默认值QuestionNumber = 0

当我输入Debug::show($this->QuizQuestion()->QuestionNumber)时,我可以看到它确实是2。在保存和发布子元素之前,我如何获得父元素属性?

我现在不知道这个模块,但通常你应该能够从当前url中获得父id。它很粗糙,但应该对你有用。

public function ItemByUrl() {
  $uri = explode('/', $_SERVER['REQUEST_URI']);
  $i = array_search('IDENTIFIER', $uri);
  if(isset($uri[$i+PARTS])) {
    $itemID = $uri[$i+PARTS];
    $item = DATAOBJECTCLASS::get()->byID($itemID);
    if($item) {
      return $item;
    }
  }
}
如果你的URL是这样的

admin/.../EditForm/field/ParentDataObject/item/67/ItemEditForm/field/ChildDataObject/item/new

你想要得到ParentID 67

IDENTIFIER将为"ParentDataObject"

PARTS为"2"

和DATAOBJECTCLASS将是"ChildDataObject"

父记录此时应该是可用的。确保先调用父方法。

在底层,elemental只是使用GridField,因此您可以搜索任何与GridField相关的文档来更好地理解这一点。

public function onBeforeWrite()
{
    parent::onBeforeWrite();
    // $this->List(); // Obj(ID = 2);
}