Skip to content

Instantly share code, notes, and snippets.

@hailwood
Last active November 6, 2015 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hailwood/f894370c658610a6d7b2 to your computer and use it in GitHub Desktop.
Save hailwood/f894370c658610a6d7b2 to your computer and use it in GitHub Desktop.
I needed a way to share one DataObject type between multiple has_many relations on the same page without the DataObject knowing how many links it had, this solution works using `AddNewInlineButton` and `GridFieldEditableColumns`. To add an additional table the only change required is another entry in the foreach on line 13.
<?php
class EditableTablePage extends Page {
private static $has_many = [
'TableRows' => 'TableRow'
];
public function getCMSFields(){
$fields = parent::getCMSFields();
Requirements::customCSS(".col-Table { display: none; }");
foreach ([1 => 'One', 2 => 'Two'] as $number => $name) {
$displayFields = [
'Column1' => 'Column One',
'Column2' => 'Column Two',
'Column3' => 'Column Three',
'Table' => function () use ($number) { return new HiddenField('Table', null, $number); }
];
/** @var GridFieldConfig $tableConfig */
$tableConfig = GridFieldConfig::create();
$tableConfig->addComponent(new GridFieldButtonRow('before'))
->addComponent(new GridFieldAddNewInlineButton('buttons-before-left'))
->addComponent(new GridFieldSortableHeader())
->addComponent(new GridFieldOrderableRows('SortOrder'))
->addComponent((new GridFieldEditableColumns())->setDisplayFields($displayFields))
->addComponent(new GridFieldDeleteAction());
$gridField = GridField::create(
"FeesTable{$name}GridField",
"Table Rows",
$this->{"Table{$name}TableRows"}(),
$tableConfig
);
$fields->addFieldToTab("Root.Table{$name}", $gridField);
}
return $fields;
}
}
<?php
class TableRow extends DataObject {
protected static $db = [
'Title' => 'Varchar(255)',
'Column1' => 'Varchar(255)',
'Column2' => 'Varchar(255)',
'Column3' => 'Varchar(255)',
'Table' => 'Int',
'SortOrder' => 'Int'
];
protected static $has_one = [
'Page' => 'Page'
];
private static $summary_fields = [
'Column1' => 'Column One',
'Column2' => 'Column Two',
'Column3' => 'Column Three',
];
protected static $default_sort = 'SortOrder';
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment