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.

Customising the CMS /

Inheriting widgets


Reply


3 Posts   2834 Views

Avatar
joshy

Community Member, 57 Posts

2 August 2009 at 10:48pm

Edited: 02/08/2009 10:49pm

Hiya,

Not sure this is the 'right' way but it certainly works with a lot less code!

If the page you are viewing has widgets, it will use them. If it doesn't have any, it will try use the parent's widgets. If the parent has none it will use the widgets of the Homepage (URL segment = 'home').

This presumes you call $Sidebar in the template and that you have set the $has_one like so:

$has_one = array('WidgetArea' => 'WidgetArea');

function Sidebar()
{
if ($this->WidgetArea()->Widgets()->Count())
{
return $this->WidgetArea();
}
else if ($this->parent()->exists() && $this->parent()->WidgetArea()->Widgets()->Count())
{
return $this->parent()->WidgetArea();
}
else
{
$home = DataObject::get_one("Page", "URLSegment = 'home'");
return $home->WidgetArea();
}
}

I apologise in advance if this has syntax errors - I am not near a SS install to test.

Cheers,

Josh

ps: my indentations are not showing. Grr...

Avatar
joshy

Community Member, 57 Posts

4 August 2009 at 9:49am

Something like this should work (untested, sorry - again, not at near a Silverstripe install):

function Sidebar()
{
   // Create a new object
   $widgets = new DataObjectSet();

   // Push this page's widgets into it
   if ($this->WidgetArea()->Widgets()->Count())
   {
      $widgets->push($this->WidgetArea());
   }
   // Push the parent widgets into it too
   if ($this->parent()->exists() && $this->parent()->WidgetArea()->Widgets()->Count())
   {
      $widgets->push($this->parent()->WidgetArea());
   }

   // ** You could potentially get the parent's parent or the homepage's or whatever too...

   // Uncomment the debug line to show the contents of the widget variable (so you know what to reference in the template)
   // Debug::show($widgets);
   return $widgets;
}

You'd then call this as a <% control Sidebar %> in your template and loop through the values (as shown in the Debug::show - currently commented out).

I hope this helps!

Cheers,

Josh

Avatar
joshy

Community Member, 57 Posts

4 August 2009 at 9:57am

It's alright - I've spent the last few weeks messing around with similar things and it did my head in - glad I can share my knowledge and make your life a bit easier :-).

Cheers,

Josh