0

我想获得一个通用函数,用于在页面模板中获取数据,如果未设置属性,则从父级或父级父级获取它等等。泛型是指独立于 db、HasOne、HasMany、ManyMany 等关系。假设我有这个用于 ManyMany,但想检测它是 Object、HasManyList 还是 ManyManyList 或一个值。有这样的内置功能吗?或者你会怎么做?

function ManyManyUpUntilHit($ComponentName){
  $Component = $this->getManyManyComponents($ComponentName);
  if($Component && $Component->exists())
  return $Component;
  $Parent = $this->Parent();
  if(is_object($Parent) && $Parent->ID != 0){
    return $Parent->ManyManyUpUntilHit($ComponentName);
  } else {
    return null;
  }
}

在模板中:

$ManyManyUpUntilHit(Teaser)
4

1 回答 1

1

Silverstripe 中没有内置的方法可以做到这一点。您将需要编写自己的函数来执行此操作。

下面是一个通过参数获取页面的 has_one、has_many 或 many_many 资源的示例,或者沿着站点树向上直到找到资源,或者我们点击根页面:

function getComponentRecursive($componentName) {

    // has_one
    if ($this->has_one($componentName)) {
        $component = $this->getComponent($componentName);
        if (isset($component) && $component->ID)
        {
            return $component;
        }
    }

    // has_many
    if ($this->has_many($componentName)) {
        $components = $this->getComponents($componentName);
        if (isset($components) && $components->count())
        {
            return $components;
        }
    }

    // many_many
    if ($this->many_many($componentName)) {
        $components = $this->getManyManyComponents($componentName);
        if (isset($components) && $components->count())
        {
            return $components;
        }
    }

    if ($this->ParentID != 0)
    {   
        return $this->Parent()->getComponentRecursive($componentName);
    }

    return false;
}
于 2013-11-17T23:18:39.990 回答