Jump to:

791 Posts in 369 Topics by 303 members

Widgets

SilverStripe Forums » Widgets » Is there a way to get the ID of the containing page for a widget?

Discuss SilverStripe Widgets.

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

Page: 1
Go to End
Author Topic: 1152 Views
  • ImacSS
    Avatar
    Community Member
    35 Posts

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

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

  • mark_s
    Avatar
    Community Member
    78 Posts

    Re: Is there a way to get the ID of the containing page for a widget? Link to this post

    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

    1152 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.