Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Widgets /

Discuss SilverStripe Widgets.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Is there a way to get the ID of the containing page for a widget?


Reply


2 Posts   1284 Views

Avatar
ImacSS

Community Member, 35 Posts

19 May 2010 at 6:16am

Is there a simple, elegant way to obtain the ID of the page containing a widget, from within that widget?

I've figured out how to get the ID of the WidgetArea, but not the containing page.

Anyone have any ideas they could throw at me? For some reason this is more difficult than I first thought it would be...

class TestWidget extends Widget
{
   static $db = array(
      'MyValue' => 'Varchar'
   );

   static $title = "Test Widget";
   static $cmsTitle = "Test Widget Widget";
   static $description = "A widget to test with.";

   // Method to handle generation of form fields for selection of widget content
   function getCMSFields()
   {
      $TxtFld = new TextField( "MyValue", "My Value" );   

      return new FieldSet( $TxtFld );
   }

   function GetContainerPageID()
   {
      return $this->parent()->ID; // This only returns the ID of the WidgetArea...
   }
}

Avatar
mark_s

Community Member, 78 Posts

19 May 2010 at 10:36pm

Hi.

A widget knows it's parent WidgetArea, but the WidgetArea doesn't know it's owner. Typically a page that contains widgets will have:

static $has_one = array("Widgets" => "WidgetArea")

or something like that. So if you want the page that owns a particular widget area, you'll need to do something like this:

$page = DataObject::get_one("Page", "WidgetsID={$widgetAreaID}");

where $widgetAreaID is $this->parent()->ID within the widget, like you have in your function, and where WidgetsID is the column in page that has the widget area (the "Widgets" in the has_one, with "ID" added to the end)

In blog module, one of the primary consumers of widgets, BlogTree has this:

static $has_one = array(
      "SideBar" => "WidgetArea",
   );

so the column will be SideBarID. In this case it will be in the BlogTree and BlogTree_Live tables.

(you'll need to quote the filter in get_one properly for some databases - I'm assuming mysql)

Hope this helps
Mark