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.
<?php
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', [
TextField::create('Name'),
TextField::create('Price')
]);
return $fields;
}
}
Here’s what the ModelAdmin that manages the Product would look like.
<?php
use MyVendor\MyNamespace\Product;
use SilverStripe\Admin\ModelAdmin;
class ProductsAdmin extends ModelAdmin {
private static $managed_models = [
Product::class
];
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.
<?php
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">
<span>$ID</span>
<span>$Name</span>
<span>$Price</span>
</div>
<% end_loop %>
Notice in the loop we're calling $Products and not $getProducts, either one should work exactly the same.
Post your comment
Comments
No one has commented on this page yet.
RSS feed for comments on this page | RSS feed for all comments