【问题标题】:Silverstripe 3.1.x getting values from ParentSilverstripe 3.1.x 从父级获取值
【发布时间】:2013-11-13 14:12:50
【问题描述】:

我想获得一个通用函数,用于在页面模板中获取数据,如果未设置属性,则从父级或父级父级获取它等等。泛型是指独立于 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)

【问题讨论】:

    标签: content-management-system silverstripe


    【解决方案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;
    }
    

    【讨论】:

    • 如果我做对了,这会以比上面的函数更不通用的方式解决问题,因为您必须在 php.ini 中指定“资源”。我想要的是一个函数,它允许我在模板中指定资源,无论它是 DB、HasOne、HasMany 还是 ManyMany 资源。
    • 我之前误会了。我已经更新了使用参数工作的答案,并为 has_one、has_many 或 many_many 工作。我已经测试了 has_one 而不是其他的。我不确定如何从 db、belongs_to 或 belongs_many_many 获取项目。
    • 抱歉,我花了很长时间才回到这里。上午我没有归属方面的用例,所以它对我很有用 - 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多