本文介绍了Silverstripe 3.1.x从父级获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个通用函数,用于获取页面模板中的数据,如果未设置该属性,则从父级或父级父级等获取该属性。与泛型我的意思是独立的关系像db,HasOne,HasMany,ManyMany。让我们说我有ManyMany,但想检测它是一个对象,HasManyList或ManyManyList或值。是什么类似这样的内置或你将如何去?

I would like to get a generic function working for getting Data in Template of a Page and if the property is not set, getting it from the Parent or Parents Parent and so on. With generic I mean independent of Relations like db, HasOne, HasMany, ManyMany. Let's say I have this for ManyMany but would like to detect if it's a Object, HasManyList or ManyManyList or a value. Is anything like this built in or how would you go about?

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)


推荐答案

没有内置的方法在Silverstripe中做到这一点。

There is no in built method to do this in Silverstripe. You will need to write your own function to do this.

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

Here is an example to get a page's has_one, has_many or many_many resource by parameter, or go up the site tree until a resource is found, or we hit a root page:

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;
}

这篇关于Silverstripe 3.1.x从父级获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 15:59