SSbits - Home page
Site by Carbon Crayon
Submit a Post >

Snippets - Little bits of code to make you happy

Check to see if a widget area has any widgets

If you want to check that a WidgetArea actually has widgets, and only display it if it has, you can add this function to your Page_Controller (where widgetBarID is the name of your widgetArea + ID)

 

function HasWidgets() {
    return DataObject::get("Widget", "ParentID = $this->WidgetbarID");
} 

Then in your template file, MyPage.ss you can use HasWidgets to check whether the WidgetArea should be rendered:

<%if HasWidgets %>
    <div id="Widgetbar">
        $Widgetbar
    </div>
<% end_if %>

You need to have added a WidgetArea to your page (called 'Widgetbar' in this example), otherwise the above will fail and you'll get a white page of death. This code will add a widgetArea to MyPage:

class MyPage extends Page {
   
    static $db = array(
    );
    static $has_one = array(
        "Widgetbar" => "WidgetArea"
    );
    function getCMSFields() {
        $fields = parent::getCMSFields();
        $fields->addFieldToTab('Root.Content.Widgets', new WidgetAreaEditor('Widgetbar'));
        return $fields;
    }
}
Chris Rowbotham avatar

Chris Rowbotham

Chris is a web designer / software developer based in Lancaster, England. He runs functional & elegant, a small company specialising in bespoke software, training and web design.

No one has commented on this page yet.

Post a comment ...

You cannot post comments until you have logged in. Login Here.

Advertisement

Site of the Month

Find SSbits on

Top Contributers

Rank Avatar Name
1 article image Aram Balakjian
2 article image Daniel Hensby
3 article image Marcus Dalgren
4 article image Hamish Campbell
5 article image njorndare
6 article image Ty Barho
7 article image Martijn van Nieuwenhoven
8 article image Darren-Lee
9 article image Roman Schmid
10 article image Matt Clegg

View full leaderboard


Advertisement