After our conversation on IRC we came up with the following alternative solution, which I will post here for the record.
This solution is quiet similar to the original answer, with the difference, that there is an additional object that handles the relation between Restaurant
and Cuisine
.
File: Restaurant.php
/**
* @method ManyManyList RestaurantCuisines
*/
class Restaurant extends Page {
private static $many_many = array(
'RestaurantCuisines' => 'RestaurantCuisine',
);
/**
* @return FieldList
*/
public function getCMSFields() {
$return = parent::getCMSFields();
$return->addFieldToTab('Root', Tab::create('Cuisines', 'The Cuisines'));
$return->addFieldToTab(
'Root.Cuisines',
GridField::create(
'RestaurantCuisines',
'The Cuisines this Restaurant offers',
$this->RestaurantCuisines(),
GridFieldConfig_RecordEditor::create()
)
);
return $return;
}
}
class Restaurant_Controller extends Page_Controller {
}
File: RestaurantCuisine.php
/**
* @property int CuisineID
* @method Cuisine Cuisine
* @method ManyManyList SubCuisines
*/
class RestaurantCuisine extends DataObject {
private static $has_one = array(
'Cuisine' => 'Cuisine',
);
private static $many_many = array(
'SubCuisines' => 'SubCuisine',
);
private static $summary_fields = array(
'getTitle' => 'Title'
);
public function getCMSFields() {
if ($this->isInDB()) {
$grid = GridField::create(
'SubCuisines',
'The Sub Cuisines of this Cuisines',
$this->SubCuisines(),
GridFieldConfig_RelationEditor::create()
);
} else {
// because this record is not saved to the DB yet, we have no ID, without ID there can be no many_many relation
$grid = ReadonlyField::create('SubCuisines', '', 'Sub Cuisines can be added after creating');
}
return FieldList::create(array(
DropdownField::create('CuisineID', 'Select a Cuisine', Cuisine::get()->map()),
$grid
));
}
/**
* overwrite getTitle and return title of Cuisine to have a nice text to display instead of the ID when displaying the save message
*/
public function getTitle() {
return $this->Cuisine() && $this->Cuisine()->exists() ? $this->Cuisine()->Title : parent::getTitle();
}
}
File: Cuisine.php
/**
* @property string Title
*/
class Cuisine extends DataObject {
private static $db = array(
'Title' => 'Varchar(255)',
);
/**
* @return FieldList
*/
public function getCMSFields() {
return FieldList::create(array(
TextField::create('Title', 'Name of Cuisine'),
));
}
}
File: SubCuisine.php
/**
* @property string Title
*/
class SubCuisine extends DataObject {
private static $db = array(
'Title' => 'Varchar(255)',
);
/**
* @return FieldList
*/
public function getCMSFields() {
return FieldList::create(array(
TextField::create('Title', 'Name of Cuisine'),
));
}
}