dongzhuxun5136 2016-07-12 22:13
浏览 36
已采纳

如何检测Silverstripe页面在Controller中作为父级或子级加载

Our Silverstripe project has the following two page types:

class MultiSectionPage extends Page {
  private static $allowed_children = array(
    'Section'
  );

  public function PageSections() {
    $PageSections = Section::get()->filter(array('ParentID' => $this->ID));
    return $PageSections;
  }
}

class Section extends Page {
  public static $allowed_children = array();
  private static $show_in_sitetree = false;
}

In the Layout/MultiSectionPage.ss template the following code loops through each child Section as a dataobject:

<% loop $PageSections %>
<% include MultiSectionPage_Section %>
<% end_loop %>

I want to make sure that if anyone accidentally links to a Section it redirects to the parent MultiSectionPage.

class Section extends Page {
  public function Link() {
    return parent::Link() . '#section-' . $this->ID;
  }
}

class Section_Controller extends Page_Controller {

  public function init(){
    parent::init();

    if(!$this->getResponse()->isFinished() && $link = $this->Link()) {
        $this->redirect($link, 301);
        return;
    }
  }
}

However using this method triggers a redirect even when viewing the MultiSectionPage as the init must get called each time the Section DataObject is rendered.

How do I detect whether a Section Controller is being loaded as a standalone parent (redirect) or as child of a MultiSectionPage ?

  • 写回答

1条回答 默认 最新

  • duankanjian4642 2016-07-13 01:01
    关注

    The Section_Controller should not be getting called when viewing the MultiSectionPage. Only the Section object is loaded when looping through PageSections. When retrieving a DataList of DataObjects only their class is loaded, not their controller.

    Note the Section_Controller should redirect to the parent page link, not the current page link. I would also recommend updating the Section Link function to return the parent link:

    class Section extends Page {
        private static $allowed_children = array();
        private static $show_in_sitetree = false;
    
        public function Link($action = null) {
            return $this->Parent()->Link($action);
        }
    }
    
    class Section_Controller extends Page_Controller {
        public function init() {
            parent::init();
    
            return $this->redirect($this->Parent()->Link(), 301);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?