From 0f207180b4d1438431a01bce7eebb0ccef3ac17e Mon Sep 17 00:00:00 2001 From: John Milmine Date: Wed, 11 Nov 2015 15:01:03 +1300 Subject: [PATCH] Making widgets able to be used in a non page controller --- code/controller/WidgetController.php | 34 +++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/code/controller/WidgetController.php b/code/controller/WidgetController.php index 1008ee5..78eced3 100644 --- a/code/controller/WidgetController.php +++ b/code/controller/WidgetController.php @@ -50,15 +50,37 @@ class WidgetController extends Controller { */ public function Link($action = null) { $id = ($this->widget) ? $this->widget->ID : null; + $segment = Controller::join_links('widget', $id, $action); - - if($page = Director::get_current_page()) { + + $page = Director::get_current_page(); + if($page && !($page instanceof WidgetController)) { return $page->Link($segment); - } - - return Controller::curr()->Link($segment); + } + + if ($controller = $this->getParentController()) { + return $controller->Link($segment); + } + + return $segment; } - + + /** + * Cycles up the controller stack until it finds a non-widget controller + * This is needed because Controller::curr returns the widget controller, + * which means any Link function turns into endless loop. + * + * @return Controller + */ + public function getParentController() { + foreach(Controller::$controller_stack as $controller) { + if (!($controller instanceof WidgetController)) { + return $controller; + } + } + return false; + } + /** * @return Widget */