database schema
Articles » Getting DataObjects and rendering them onto a template in Silverstripe

Getting DataObjects and rendering them onto a template in Silverstripe

15 April, 2020

Let’s say we have a DataObject called ‘Product’ and this doesn’t have any relationship to any page type but rather managed through a ModelAdmin.


namespace MyVendor\MyNamespace;

use SilverStripe\Forms\TextField;
use SilverStripe\ORM\DataObject;

class Product extends DataObject {
    private static $table_name = 'Product';

    private static $db = [
        'Name' => 'Varchar',
        'Price' => 'Varchar'

    public function getCMSFields() {
        $fields = parent::getCMSFields();

        $fields->addFieldsToTab('Root.Main', [

        return $fields;


Here’s what the ModelAdmin that manages the Product would look like.


use MyVendor\MyNamespace\Product;
use SilverStripe\Admin\ModelAdmin;

class ProductsAdmin extends ModelAdmin {

    private static $managed_models = [

    private static $url_segment = 'products';

    private static $menu_title = 'Products';


Now we want to get all 'Product's and show them on one of our page templates. What we can do is write a method on the PageController of that page type that would return all Products.


namespace MyVendor\MyNamespace\Pages;

use MyVendor\MyNamespace\Product;
use PageController;    

class MyPageController extends PageController {

    public function getProducts() {
        $products = Product::get();

        return $products;



After writing our 'getProducts' method above, we can then go to the page template of that page type and call 'getProducts' in a loop like so and render each Product.

<% loop $Products %>
    <div class="product">
<% end_loop %>

Notice in the loop we're calling $Products and not $getProducts, either one should work exactly the same. 


Post your comment


No one has commented on this page yet.

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