Tables in SilverStripe that follow the Model View Controller pattern

This SilverStripe code snippet shows how to maintain seperation between Model/Controller and View when generating tabular data. It is easy to resort to quickly including some HTML codes in the Model/Controller when trying to create a table. However, this example shows that it isn't necessary and the seperation between Model/Controller and view can be maintained when generating tables. Although the example doesn't specifically show it, both the row and column sizes are flexible.

One short note, due to the way templates handle nested <% control %> statements it is necessary to include all the data values in the RowHeadings control.


class TableExample extends Page {
    // Define row and column variables
    public static $row = array("1", "2", "3");
    public static $col = array("a", "b", "c");

    // Create rows with headings
    function RowHeadings() {
        $items = new DataObjectSet();
        foreach(self::$row as $r) {
            $rowItems = new DataObjectSet();       
            foreach(self::$col as $c) {
                // Create cell values for control
                $rowItems->push(new ArrayData(array("Value" => $r . $c)));
            // Add heading and values to ArrayData object
            $items->push(new ArrayData(array("Heading" => $r, "Values" => $rowItems)));
        return $items;

    // For colHeadings only Headings are required.
    function ColHeadings() {
        $items = new DataObjectSet();
        foreach(self::$col as $c) {
            $items->push(new ArrayData(array("Heading" => $c)));
        return $items;

    <% control ColHeadings %>
        <th scope="col">$Heading</th>
    <% end_control %>
    <% control RowHeadings %><tr>
        <th scope="row">$Heading</th>
        <% control Values %>
        <% end_control %>
    </tr><% end_control %>


Post your comment


No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments