Note: The latest version of SS3 works differently to this article describes. Please check out this article for more up to date info, or check the silverstripe.com help files
Using the Silverstripe 3 GridField
In SS3, the ComplexTableField, TableListField, and TableField have all gone, which also means the handy plugin 'dataObjectManager' no longer works. Instead, it's being replaced with the DataGrid / GridField. When you come to upgrade your SS2 site to SS3, changing to GridFields will be the biggest task.
This is just a short code sample. A Gallery page 'has_many' gallery items (the photographs). The gallery page needs a section in the CMS to manage the photos.
This is the page type - GalleryPage
class GalleryPage extends Page {
public static $db = array(
);
public static $has_many = array(
'GalleryItems' => 'GalleryItem' // link the gallery items
);
function getCMSFields() {
$fields = parent::getCMSFields();
$config = GridFieldConfig::create() // create a config object for the grid field
$config->addComponent(new GridFieldFilter()); // add search filter to grid field
$config->addComponent(new GridFieldDefaultColumns()); // show default columns
$config->addComponent(new GridFieldAction_Delete()); // add a delete button
$config->addComponent(new GridFieldAction_Edit()); // add an edit button
// we also have to define a template for the 'edit'/'add' window:
$config->addComponent($gridFieldForm = new GridFieldPopupForms());
$gridFieldForm->setTemplate('CMSGridFieldPopupForms');
$itemsInGrid = DataList::create('GalleryItem'); // get a list of object you want to show
$gridField = new GridField("GalleryItems", "Images in this gallery",
$gridField->setDisplayFields(array(
'ID' => 'ID',
'Title' => 'Title of the Photo',
'Image.URL' => 'Image URL',
));
$fields->addFieldToTab("Root.Images", $gridField); // add the grid field to a tab in the CMS
return $fields;
}
}
class GalleryPage_Controller extends Page_Controller {
public static $allowed_actions = array (
);
public function init() {
parent::init();
}
}
And this is the code for the images within the gallery - GalleryItem
class GalleryItem extends DataObject {
static $db = array (
'Title' => 'Varchar',
'Date' => 'Varchar',
'Credit' => 'Varchar'
);
static $has_one = array (
'GalleryPage' => 'GalleryPage',
'Image' => 'File'
);
}
Defining the relationship between the gallery and the galelry item is the same as in Silverstripe 2. However, the DataList and GridField is all new.
Note: I'm currently working with an early pre release version of Silverstripe 3, and the code here is a start point and not everything works. For example, I haven't yet found a way of adding new objects. It is also necessary to define a lot of config options before the gridfield works, it may be that in the final release there is a quicker easier way of doing this, with less lines of code. I'll keep you posted!